C++ 转发函数指针
我惊讶地发现,显然C++ 转发函数指针,c++,gcc,c++11,g++,C++,Gcc,C++11,G++,我惊讶地发现,显然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); } #包括 模板 空心钢筋(T&&); 模板
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);
}
#包括
模板
空心钢筋(T&&);
模板
无效foo(T&v){
棒(标准:正向(v));
}
int 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));
forward.cc:void foo(T&)[with T=int(&)(])的实例化中:
转发。抄送:12:13:从这里开始需要
forward.cc:8:23:错误:调用“forward(int(&))时没有匹配的函数”
棒(标准:正向(v));
^
转发。抄送:8:23:注:候选人:
在/usr/include/c++/4.8.2/bits/stl_pair.h:59:0中包含的文件中,
从/usr/include/c++/4.8.2/utility:70,
从前进。抄送:1:
/usr/include/c++/4.8.2/bits/move.h:76:5:注意:模板constexpr\u Tp&&std::forward(typename std::remove\u reference::type&)
转发(typename std::remove\u reference::type&\u t)无例外
^
/usr/include/c++/4.8.2/bits/move.h:76:5:注意:模板参数推断/替换失败:
forward.cc:8:23:注意:无法推断模板参数“\u Tp”
棒(标准:正向(v));
^
在/usr/include/c++/4.8.2/bits/stl_pair.h:59:0中包含的文件中,
从/usr/include/c++/4.8.2/utility:70,
从前进。抄送:1:
/usr/include/c++/4.8.2/bits/move.h:87:5:注意:模板constexpr\u Tp&&std::forward(typename std::remove\u reference::type&)
转发(typename std::remove_reference::type&&__t)无例外
^
/usr/include/c++/4.8.2/bits/move.h:87:5:注意:模板参数推导/替换失败:
forward.cc:8:23:注意:无法推断模板参数“\u Tp”
棒(标准:正向(v));
也许我被新的通用引用语法误导了,或者我的GCC日子不好过
我使用的是GCC 4.8.2。std::forward()
使用的参数类型无法推断。您必须手动提供模板参数:
std::forward(v);
// ^^^
嗯,那很快。我也很傻。回答这个问题,我会接受的。
std::forward<T>(v);
// ^^^