How remove_reference disable template argument deductions?

给你一囗甜甜゛ 提交于 2019-12-08 21:22:47

问题


According to this link, template argument deduction disallowed for std::forward and std::remove_reference is helping us to achieve that. But how does using remove_reference prevent template deduction from happening here?

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

回答1:


S in the expression typename std::remove_reference<S>::type is a non-deduced context (specifically because S appears in the nested-name-specifier of a type specified using a qualified-id). Non-deduced contexts are, as the name suggests, contexts in which the template argument cannot be deduced.

This case provides an easy example to understand why. Say I had:

int i;
forward(i);

What would S be? It could be int, int&, or int&& - all of those types would yield the correct argument type for the function. It's simply impossible for the compiler to determine which S you really mean here - so it doesn't try. It's non-deducible, so you have to explicitly provide which S you mean:

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


来源:https://stackoverflow.com/questions/37418089/how-remove-reference-disable-template-argument-deductions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!