使用模板化函数作为模板参数

时间:2018-03-02 02:55:44

标签: c++ templates

我正在编写一个具有重复调用函数的类,并决定将其作为模板参数赋予函数。 作为我所谈论的具体例子,请考虑以下类:

#include <array>

template<double (*func)(std::array<double,3>)>
class MyClass
{

public:
    MyClass()
    {
        std::array<double,3> v {{0.1,0.2,0.1}};
        func(v);
    }
};

然后可以使用函数进行实例化,例如:

double func(std::array<double,3> x)
{
    return x[0]*x[0]+x[1];
}

int main()
{
    MyClass<func> entity;
}

但是,我需要使用不同类型可调用的函数(函数中的操作当然适用于所有函数),也就是说我希望将此函数模板化,如:

template<typename scalartype, typename vectype>
scalartype func1(vectype x)
{
    scalartype res = x[0]*x[0]+x[1];
    return res;
}

我仍然可以使用它作为模板参数,但是函数参数和返回类型然后在类中修复。那么如何在类中提供模板化功能?例如,我可以用std::vector四个整数调用它并返回一个整数。

我尝试使用模板模板参数,但我甚至无法弄清楚如何使用两个模板参数(因为它们似乎只允许模板...语法)。对不起,如果不清楚,我还是新人。

1 个答案:

答案 0 :(得分:1)

您可以将模板函数放在一个类中,然后将该类传递给MyClass

#include <iostream>
#include <vector>
#include <array>

struct templateHolder {
    template <typename vectype, typename scalartype = typename vectype::value_type>
    static scalartype func(vectype x) {
        return x[0] + x[1];
    }
};

template<typename T>
class MyClass
{

public:
    MyClass()
    {
        std::vector<int> vec {1,2};
        std::cout << T::func(vec) << std::endl;

        std::array<double, 2> arr {0.5, 3.33};
        std::cout << T::func(arr) << std::endl;
    }
};

int main() {
    MyClass<templateHolder> foo;
    return 0;
}

我选择从scalartype中推断vectype。不一定是你想要的,但它可能是一个选项,取决于你的用例。

相关问题