我一直试图了解C ++选择模板或成员函数的方式。考虑以下代码示例:
#include <iostream>
#include <string>
struct Test
{
template<typename X>
explicit Test( X&& s){ std::cout << "1" << std::endl;}
explicit Test( const std::string& s) { std::cout << "2"<< std::endl; }
explicit Test( std::string&& s) { std::cout << "3"<< std::endl; }
};
int main ()
{
std::string line = "TEST";
Test test( line );
}
我在控制台上打印了“ 1”。如果它是与参数类型匹配的非模板,为什么不选择“ 2”?
构造函数模板的参数声明为转发参考。当传递左值时,例如line
,模板参数X
推导为std::string&
,在引用折叠后,参数类型为std::string&
,即对non-const的左值引用std::string
。这是完全匹配,并在重载分辨率方面胜出。
另一方面,构造函数采用const std::string&
要求对参数进行const限定,并且构造函数采用std::string&&
不能与左值一起使用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句