模板参数在具有相同数据类型的单个typename的构造函数中不起作用

问题描述 投票:0回答:1

在尝试使用std::forward时,写了一个简单的person类,它只有nameaddress以及初始化它们的构造函数。下面是类定义。

class person {
   std::string name;
   std::string address;
public:

template<class T1, class T2>
   person(T1&& _name, T2&& _address) : name{ std::forward<T1>(_name) }, 
   address{ std::forward<T2>(_address) } { std::cout << "Template Constructor" << std::endl; }

 // This is not working if passed by rvalue
template<class T>
 person(T&& _name, T&& _address) : name{ std::forward<T>(_name) }, address{ std::forward<T>(_address) } { std::cout << "Single template Constructor" << std::endl; }

};
int main(){

    person p{"john doe","Somewhere"}; // This doesn't work without the template constructor which takes two typenames
    std::string name="user";
    std::string address = "blah";

    person p2{name, address}; // This of course works with just template<class T>.
}

Intellisense显示错误为没有no constructor of "person" can take two arguments "const char[9], const char[10]"template<class T1, class T2>。为什么这不仅仅是“const char []”并且与template<class T>合作?在这种情况下,有没有办法让template<class T>工作?

c++ templates
1个回答
2
投票

说你有这个:

template <typename T>
void fn(T&&) {
  // ...
}

int main(int, char**) {
  fn("abc");

  return 0;
}

在我看来,你期待T解决const char []const char *which in this context can be considered the same type)。实际上,T解决了const char (&) [4],保留了大小信息。这就是为什么你不能使用单个模板构造函数和两个不同大小的C字符串。

如果您尝试使用两个相同大小的C字符串调用单个模板构造函数,您将看到它的工作原理。

© www.soinside.com 2019 - 2024. All rights reserved.