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

use*_*257 5 c++ functor c++11

我有一些重载函数,例如

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)

Com*_*sMS 2

只要不同重载的签名与您的问题中的一样统一,就可以通过使用函数指针值作为模板参数来完成:

template<typename T>
struct create_functor {
    template<T(*fct)(T)>
    struct functor {
        T operator()(T n) { return fct(n); }
    };
};

create_functor<int>::functor<a> func_a_int;
create_functor<float>::functor<a> func_a_float;

std::cout << func_a_int(42) << func_a_float(3.14f) << std::endl;
Run Code Online (Sandbox Code Playgroud)