c++ - 将指向模板函数的指针作为函数参数传递?

标签 c++ templates operator-overloading

假设我想要一个 C++ 函数对两个输入执行算术运算,将它们视为给定类型:

伪:

function(var X,var Y,function OP)
{
 if(something)
  return OP<int>(X,Y);
 else if(something else)
  return OP<double>(X,Y);
 else
  return OP<string>(X,Y);
}

适合 OP 的函数可能是这样的:

template <class T> add(var X,var Y)
{
 return (T)X + (T)Y; //X, Y are of a type with overloaded operators
}

那么,问题是函数的签名是什么样的?如果运算符函数是非模板化的,我可以做到,但我对这种额外的复杂性感到困惑。

最佳答案

模板函数不能作为模板参数传递。在将它传递给另一个模板函数之前,您必须手动推导此函数的模板参数。例如,你有函数

T sum(T a, T b)
{
    return a + b;
}

您想将它传递给 callFunc:

template<typename F, typename T>
T callFunc(T a, T b, F f)
{
    return f(a, b);
}

你不能简单地写

int a = callFunc(1, 2, sum);

你必须写

int a = callFunc(1, 2, sum<int>);

为了能够在不编写 int 的情况下传递 sum,您必须编写一个仿函数 - 带有 operator() 的结构或类,它将调用您的模板函数。然后你可以将这个仿函数作为模板参数传递。这是一个例子。

template<class T>
T sum(T a, T b)
{
    return a + b;
}
template<class T>
struct Summator
{
    T operator()(T a, T b)
    {
        return sum<T>(a, b);
    }
};
template<template<typename> class TFunctor, class T>
T doSomething(T a, T b)
{
    return TFunctor<T>()(a, b);
    //Equivalent to this:
    //TFunctor<T> functor;
    //return functor(a, b);
}


int main()
{
    int n1 = 1;
    int n2 = 2;
    int n3 = doSomething<Summator>(n1, n2); //n3 == 3
    return 0;
}

关于c++ - 将指向模板函数的指针作为函数参数传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1282914/

相关文章:

c++ - 将模板函数指针作为模板参数传递给模板过于冗长

c++ - 使用引用而不是重载运算符

c++ - 在 C++ 中重载间接运算符

swift - 为 Swift 中的运算符转义闭包

c++ - 检测类型是否抛出

c++ - 遍历C++表达式树以将表达式更改为NNF

C++比较,结果如何?

C++、std::copy 和模板

c++ - 如何在模板中添加 const 限定符

c++ - vector 迭代和删除