模板函数指针重载

template function pointer overloading

我有一个类似

的模板函数
template<typename T> T ABS(const T& DiIN){
    return (0 > DiIN) ? T(DiIN * (-1)) : T((DiIN));
}

template<typename T> T ADD(const T DiIN1, const T DiIN2) {
    return DiIN1 + DiIN2;
}

我需要使用单个函数指针调用函数 ABS and/or ADD。 目前我使用两个不同的函数指针名称,但发现当我包含更多具有不同参数长度的模板函数时,它变得越来越复杂。

我目前的实现就像

template<typename T>
struct test {
    std::string funcName;
    T(funcptr1 *)(T);
    T(funcptr2 *)(T, T);
};

test<int> ltest[] = { {"ABS", ABS, NULL}, {"ADD", NULL, ADD} };

有没有办法 1)使用单一的函数指针 2) 摆脱初始化 test<int> 并使用 test<T> 以便我可以在运行时使用任何变量类型?

我正在寻找像

这样的简单初始化
template<> //template<typename T>
test<T> ltest[] = = { {"ABS", ABS}, {"ADD", ADD}, ..... };

Is there a way to use a single function pointer?

可能有一种使用 std::function 的方法。但是,您可以通过提供一些构造函数来获得所需的简单性。

template <typename T>
struct test {

   using function1_type = T(*)(T);
   using function2_type = T(*)(T, T);

   test(std::string fname, function1_type f1) : funcName(fname), funcptr1(f1), funcptr2(nullptr) {}
   test(std::string fname, function2_type f2) : funcName(fname), funcptr1(nullptr), funcptr2(f2) {}
   test(std::string fname, function1_type f1, function2_type f2) : funcName(fname), funcptr1(f1), funcptr2(f2) {}

    std::string funcName;
    function1_type funcptr1;
    function2_type funcptr2;
};

现在,您将可以使用:

test<int> ltest[] = { {"ABS", ABS}, {"ADD", ADD}, {"MIXED", ABS, ADD} };

如果你想禁止使用{"MIXED", ABS, ADD}构造一个对象,你可以删除最后一个构造函数。

顺便说一句,为了使用上面的内容,您需要修改 ABSADD 以便参数类型没有 constconst&.他们需要:

template<typename T> T ABS(T DiIN){
    return (0 > DiIN) ? T(DiIN * (-1)) : T((DiIN));
}

template<typename T> T ADD(T DiIN1, T DiIN2) {
    return DiIN1 + DiIN2;
}

Is there a way to get rid of the initialization test<int> and use test<T> so that I can use any variable type during runtime?

不,你不能那样做。用于实例化模板的类型必须在编译时已知。