简体   繁体   English

专门针对具有不同签名的功能使用模板吗?

[英]Specializing a template on functions with different signatures?

I have a template that requires that I pass it a functor as a type parameter in order to perform some calculations. 我有一个模板,要求我将函子作为类型参数传递给它,以便执行一些计算。 I would like to specialize this functor based on another function that I want to use to actually perform the calculations. 我想基于另一个我想用来实际执行计算的函数来专门研究这个函子。 Basically, I want to do this (which is not legal, I'm redefining the functor): 基本上,我想这样做(这是不合法的,我在重新定义函子):

template<typename T, int (*func)(int)>
struct Functor
{
    T val;
    int operator()(int x) { return func(2); }
};

template<typename T, int (*func)(int, int)>
struct Functor 
{
    T val;
    int operator()(int y) { return func(y, 2); }
};

Component<Functor<calculationFunction1>> comp1;
Component<Functor<calculationFunction2>> comp2;

auto result1 = comp1.Compute();
auto result2 = comp2.Compute();

I've tried using partial specialization to get this to work as well, but that doesn't seem to be legal, either. 我尝试使用部分专业化来使其也正常工作,但这似乎也不合法。 I'm not sure if it's possible to get what I want, since the two functions have differing signatures. 我不确定是否可以获得我想要的东西,因为这两个函数具有不同的签名。 What's the best way to achieve what I'm trying to do here? 实现我在这里要做的最好的方法是什么?

How about: 怎么样:

template<typename T, typename SOME_FUNC_TYPE, SOME_FUNC_TYPE func >
struct Functor {};

typedef int (*SingleArgFunc)(int);
typedef int (*DoubleArgFunc)(int,int);

template<typename T, SingleArgFunc func>
struct Functor<T, SingleArgFunc, func>
{
  T val;
  int operator()(int x) { return func(2); }
};

template<typename T, DoubleArgFunc func>
struct Functor<T, DoubleArgFunc, func>
{
  T val;
  int operator()(int y) { return func(y, 2); }
};

int calculationFunction1 (int) { return 0; }
int calculationFunction2 (int, int) { return 0; }

template <typename FUNCTOR>
struct Component
{
  int Compute (void) { return FUNCTOR()(0); }
};

Component<Functor<int, decltype(&calculationFunction1), calculationFunction1>> comp1;
Component<Functor<int, decltype(&calculationFunction2), calculationFunction2>> comp2;

auto result1 = comp1.Compute();
auto result2 = comp2.Compute();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM