从std::function复制模板参数

Copying template arguments from std::function

本文关键字:参数 function std 复制      更新时间:2023-10-16

我想创建一个模板化类,其变量模板参数与给定的std::function相同。例如

template <typename T>
struct function_traits : public function_traits<decltype(&T::operator())> {};
template <typename ClassType, typename ReturnType, typename... Args>
struct function_traits<ReturnType(ClassType::*)(Args...) const> {
    template <template<typename... TArgs> class T>
    using ArgsCopy = T<Args...>;
};
template <typename... Args>
class _forwarder {
public:
    using cb = std::function<void(Args...)>;
    void operator()(Args... args) {
        my_cb(args...);
    }
private:
    cb my_cb;
};
template <typename T>
using Forwarder = function_traits<T>::ArgsCopy<_forwarder>;

我将这样使用这个类

using cb_test = std::function<void(int, float, std::string)>;
Forwarder<cb_test> fwd;
fwd(5, 3.2, "hello");

Visual Studio抛出编译错误:error C2061: syntax error: identifier ' argscope '。我该如何解决这个问题?

微软的编译器没有完全遵循这里的标准,添加template应该可以工作:

template <typename T>
using Forwarder = function_traits<T>::template ArgsCopy<_forwarder>;

但是如果你想让你的代码是可移植的,添加typename:

template <typename T>
using Forwarder = typename function_traits<T>::template ArgsCopy<_forwarder>;