c++ - remove_reference 如何禁用模板参数推导?

标签 c++ templates c++11 perfect-forwarding

根据 this link , std::forward 不允许模板参数推导,而 std::remove_reference 正在帮助我们实现这一目标。但是,使用 remove_reference 如何防止此处发生模板推导?

template <class S>
S&& forward(typename std::remove_reference<S>::type& t) noexcept
{
    return static_cast<S&&>(t);
}

最佳答案

S在表达式 typename std::remove_reference<S>::type 中是一个非推导上下文(特别是因为 S 出现在使用 qualified-id 指定类型的nested-name-specifier 中).顾名思义,非推导上下文是无法推导模板参数的上下文。

这个案例提供了一个简单的例子来理解为什么。假设我有:

int i;
forward(i);

什么会 S是?可能是 int , int& , 或 int&& - 所有这些类型都会为函数产生正确的参数类型。编译器根本不可能确定哪个 S你真的是说这里 - 所以它不会尝试。它是不可推导的,因此您必须明确提供哪个 S你的意思是:

forward<int&>(i); // oh, got it, you meant S=int&

关于c++ - remove_reference 如何禁用模板参数推导?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37418089/

相关文章:

python - 在 C++ 中打开 LAS 文件输出看似不正确的值

node.js - Derbyjs 模板错误

c++ - 如何从 OS X 终端编译带有多个类文件的 C++ 程序?

c++ - 如何使用 pthreads 和条件变量改进多线程应用程序中的实时行为?

c++ - 关闭 HANDLES 和其他 WINAPI 的模板类?

templates - 如何获取 D 模板中函数别名的名称?

c++ - 成员函数作为函数模板的参数

c++ - 仍在执行时调用 std::function 析构函数

c++ - "Overloading"带有 SFINAE 的构造函数

c++ - Visual Studio 2013 Update 2 中的 C++ 改进是什么?