简体   繁体   English

具有通用引用的成员函数模板将不接受左值

[英]Member function template with universal reference won't accept lvalues

I've been trying to use a template member function to set a value inside of my class. 我一直在尝试使用模板成员函数在我的类中设置一个值。 I wanted to use a universal reference so that I could accept any variant of the correct type (eg T , T& , T&& , const T , const T& , const T&& ) 我想使用通用引用,以便我可以接受任何正确类型的变体(例如TT&T&&const Tconst T&const T&&

However, it seems that my member function will only accept rvalues, unlike a free function accepting a universal reference. 但是,似乎我的成员函数只接受rvalues,而不像接受通用引用的自由函数。

template <typename T>
class Foo{
public:
    void memberURef(T&& t){
        val = std::forward<T>(t);
    }
private:
    T val;
};


template <typename T>
void freeURef(T&& t){

}

int main() {
    int lval = 1;
    const int clval = 1;
    freeURef(lval); // fine
    freeURef(clval); // fine

    Foo<int> foo;
    foo.memberURef(2);
    foo.memberURef(lval); //error: cannot bind 'int' lvalue to 'int&&'
    foo.memberURef(clval); //error: no matching function for call to 'Foo<int>::memberURef(const int&)'
    return 0;
}

In the code given, Foo is instantiated as Foo<int> . 在给出的代码中, Foo被实例化为Foo<int> Once this happens, the class template is instantiated as shown: 一旦发生这种情况,就会实例化类模板,如下所示:

class Foo{
public:
    void memberURef(int&& t){       // Uh oh!
        val = std::forward<int>(t);
    }
private:
    int val;
};

Notice how the member function is no longer a template, and therefore no longer accepts a universal reference, but an rvalue reference. 注意成员函数不再是模板,因此不再接受通用引用,而是接受rvalue引用。 In order to make a member function that accepts a universal reference, the Foo class would need to be modified as follows: 为了使成员函数接受通用引用,需要修改Foo类,如下所示:

template <typename T>
class Foo{
public:
    template <typename L>
    void memberURef(L&& t){
        val = std::forward<L>(t);
    }
private:
    T val;
};

That way, memberURef is still a function template after the class template has been instantiated, and it thus still accepts a universal reference. 这样,在实例化类模板之后, memberURef仍然是一个函数模板 ,因此它仍然接受通用引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM