繁体   English   中英

使用 rvaule 引用作为参数的函数模板重载不起作用?

[英]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&

如何选择右值重载? 如果参数是i不是的右值,那会有所帮助。

它不是纯右值(它是一个命名变量),也不是 xvalue。

如果您只想拦截B = int的情况,为什么不直接将参数类型设为int 使用int&&只会根据定义匹配右值。

正如评论中所讨论的,您不能简单地将转发引用B&&替换为右值引用int&& (或代替int任何其他具体类型),因为转发引用在参数推导过程中得到特殊处理(请参阅此处并搜索“转发引用” ,这是一个特例)。

您需要两个重载: const ref const int&和 rvalue ref int&& ,以涵盖与原始转发引用相同的情况。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM