相关疑难解决方法(0)

将重载函数转换为模板仿函数

我有一些重载函数,例如

int a(int) {/*...*/}
float a(float) {/*...*/}
/* ... */
int b(int) {/*...*/}
float b(float) {/*...*/}
/* ... */
Run Code Online (Sandbox Code Playgroud)

我的目标是将这些函数包装到一个仿函数对象中:

template <typename T>
struct func_a {
    auto T operator()(T t) -> decltype(a(t)) {return a(t);}
};
Run Code Online (Sandbox Code Playgroud)

是否有一种方法可以将重载函数作为参数在其他模板上定义上述模板结构?像这样的东西:

template </* pointer to an overloaded function f */>
struct create_functor {
    template <typename T>
    struct func {
        auto operator()() -> decltype(f(t)) {return f(t);}
    }
};
Run Code Online (Sandbox Code Playgroud)

所以我可以在编译时生成结构,如:

typedef create_functor<a>::func<int> func_a_int;
typedef create_functor<a>::func<float> func_a_float;
typedef create_functor<b>::func<int> func_a_int;
typedef create_functor<b>::func<float> func_a_float;
Run Code Online (Sandbox Code Playgroud)

c++ functor c++11

5
推荐指数
1
解决办法
501
查看次数

标签 统计

c++ ×1

c++11 ×1

functor ×1