[英]function template overload with rvaule reference as argument does not work?
当输入不是右值时,带有 && 作为参数的函数模板似乎无法重载。 请参阅此处作为示例:
template<typename A, typename B>
void test_tp_func(A&& a, B&& b)
{
std::cout<<"tp1(" << a << "," << b << ")\n";
}
template<typename A>
void test_tp_func(A&& a, int&& b)
{
std::cout<<"tp2(" << a << "," << b << ")\n";
}
int main()
{
test_tp_func(1, 2);
int i{10};
const int& ir = i;
test_tp_func(2, ir);
test_tp_func(2, std::move(i));
}
输出是:
tp2(1,2)
tp1(2,10)
tp2(2,10)
我们可以看到test_tp_func(2, ir);
根本没有使用过载。 如何确保它使用test_tp_func(A&& a, int&& b)
? 一种方法是添加 enable_if_t 在 B 为 int 时禁用原始模板。 但是,原始模板test_tp_func(A&& a, B&& b)
是在我无法控制的文件中定义的。
更新了示例以实际使用 const&
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.