首页 > 解决方案 > 为什么通用引用必须对成员函数使用模板而不是类?

问题描述

例如:这不是通用参考:

template<typename T>
class C {
  public:
    void gogo(T&& c);
};

但这是:

template<typename A>
class C {
  public:
    template<typename B>
    void gogo(B&& par);
}

标签: c++c++11

解决方案


在第二个片段中,B&& par不一定是通用参考。B仅当您让编译器在调用时进行推断时,它才被认为是通用的:

C<float> c;
c.gogo(42); // T is deduced as int, `par` acts as an universal reference.
c.gogo<int>(42); // T is fixed, `par` is a regular rvalue reference.

由于在第一个代码段T中,调用时总是固定的,所以引用永远不会通用。

C<int> c; // Must specify T here, there's no way for it to be deduced.
c.gogo(42); // T is fixed, `par` is a regular rvalue reference.

推荐阅读