c++ - 如何编写同时接受 && 和 const& 的模板函数?

标签 c++ templates c++11 move-semantics

例如

template<typename T> void f(T&& t) {}
template<typename T> void f(T const& t) {}

当我打电话

int i;
f(i); // call f(T&&) which I expect to call f(T const&), how to solve it?
f(10); // call f(T&&), that is fine

最佳答案

这是一种方式:

#include <type_traits>

template<typename T>
typename std::enable_if< !std::is_lvalue_reference<T>::value >::type
f(T&& t) {}

template<typename T> void f(T const& t) {}

另一种可能性是标签分派(dispatch):

template<typename T>
void f_(const T&, std::true_type) { std::cout << "const T&\n"; }
template<typename T>
void f_(T&&, std::false_type) { std::cout << "T&&\n"; }

template<typename T>
void f(T&& t)
{
    f_(std::forward<T>(t), std::is_lvalue_reference<T>{} );
}

关于c++ - 如何编写同时接受 && 和 const& 的模板函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26179731/

相关文章:

c++ - 在构建时指定模板参数

linux - 编写 C++ 安装程序文件

c++ - 函数的多重定义

c++ - 无法使用 lambda 函数创建 unordered_set

c++ - 作业dup2函数

C++ 随机数猜谜游戏错误

c++ - 使用 C++ 从 32 位进程访问 64 位 dll

C++ 使用 std::map 计算实例/直方图

ios - 在 iPad 中从基于 Window 的应用程序转换为基于 View 的应用程序

c++ - 在 C++ 中重新创建函数签名并通过模板包进行调用