Budskii
Budskii

Reputation: 119

C++ template specialization rvalue

I'm learning C++ and have a little problem with template specialization. I need to call Variable.Set() a lot so, I made the function take in references so it doesn't spend a lot of time copying the string. But then the problem I have is Variable.Set<int>(5); causes error because the parameter is an rvalue and I don't know the solution for this.

error C2664: 'void Variable::Set(int &)': cannot convert argument 1 from 'int' to 'int &'

void main()
{
    Variable var;
    var.Set<int>(5);
}

struct Variable
{
    int integer;
    float floating;
    std::string string;

    template<typename T> void   Set(T& v);
    template<> void             Set<int> (int& v) { integer = v; }
    template<> void             Set<float> (float& v) { floating = v; }
    template<> void             Set<std::string> (std::string& v) { string = v; }
};

Upvotes: 0

Views: 301

Answers (1)

twynn
twynn

Reputation: 34

You need to change your parameters to constant references (const& as mentioned in Praetorian's comment)

From this link: http://www.codesynthesis.com/~boris/blog/2012/07/24/const-rvalue-references/

while a const lvalue reference can bind to an rvalue, a const rvalue reference cannot bind to an lvalue

Upvotes: 1

Related Questions