转发函数指针

Forwarding a function pointer

本文关键字:指针 函数 转发      更新时间:2023-10-16

我很惊讶地发现显然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。

std::forward<T>()采用无法推断类型的参数。您必须手动提供模板参数:

std::forward<T>(v);
//          ^^^