【发布时间】:2021-07-06 21:52:27
【问题描述】:
当输入不是右值时,以 && 作为参数的函数模板似乎无法重载。以here为例:
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&
【问题讨论】: