我很惊讶地发现显然std::forward
不能与任意类型一起使用,尽管文档表明这一点。
#include <utility>
template<typename T>
void bar(T&&);
template<typename T>
void foo(T&& v) {
bar(std::forward(v));
}
int main() {
foo(main);
}
产生
forward.cc: In instantiation of 'void foo(T&&) [with T = int (&)()]':
forward.cc:12:13: required from here
forward.cc:8:23: error: no matching function for call to 'forward(int (&)())'
bar(std::forward(v));
^
forward.cc:8:23: note: candidates are:
In file included from /usr/include/c++/4.8.2/bits/stl_pair.h:59:0,
from /usr/include/c++/4.8.2/utility:70,
from forward.cc:1:
/usr/include/c++/4.8.2/bits/move.h:76:5: note: template<class _Tp> constexpr _Tp&& std::forward(typename std::remove_reference<_From>::type&)
forward(typename std::remove_reference<_Tp>::type& __t) noexcept
^
/usr/include/c++/4.8.2/bits/move.h:76:5: note: template argument deduction/substitution failed:
forward.cc:8:23: note: couldn't deduce template parameter '_Tp'
bar(std::forward(v));
^
In file included from /usr/include/c++/4.8.2/bits/stl_pair.h:59:0,
from /usr/include/c++/4.8.2/utility:70,
from forward.cc:1:
/usr/include/c++/4.8.2/bits/move.h:87:5: note: template<class _Tp> constexpr _Tp&& std::forward(typename std::remove_reference<_From>::type&&)
forward(typename std::remove_reference<_Tp>::type&& __t) noexcept
^
/usr/include/c++/4.8.2/bits/move.h:87:5: note: template argument deduction/substitution failed:
forward.cc:8:23: note: couldn't deduce template parameter '_Tp'
bar(std::forward(v));
也许我被新的通用引用语法误导了,或者我的GCC正在度过糟糕的一天。
我正在使用GCC 4.8.2。
答案 0 :(得分:5)
std::forward<T>()
采用无法推导出类型的参数。您必须手动提供模板参数:
std::forward<T>(v); // ^^^