将指针到模板函数作为函数参数传递?

Mr.*_*Boy 8 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);
}
Run Code Online (Sandbox Code Playgroud)

适合OP的函数可能如下:

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

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

izo*_*fif 6

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

T sum(T a, T b)
{
    return a + b;
}
Run Code Online (Sandbox Code Playgroud)

你想将它传递给callFunc:

template<typename F, typename T>
T callFunc(T a, T b, F f)
{
    return f(a, b);
}
Run Code Online (Sandbox Code Playgroud)

你不能简单地写

int a = callFunc(1, 2, sum);
Run Code Online (Sandbox Code Playgroud)

你必须写

int a = callFunc(1, 2, sum<int>);
Run Code Online (Sandbox Code Playgroud)

为了能够在不编写int的情况下传递sum,您必须编写一个functor - struct或类,其中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;
}
Run Code Online (Sandbox Code Playgroud)


CB *_*ley 5

你在找这个吗?

template<class T> T add(T X, T Y)
{
    return X + Y;
}
Run Code Online (Sandbox Code Playgroud)

或者您是否正在寻找称为 add 之类的东西?

template<class T, class F>
T Apply(T x, T y, F f)
{
    return f( x, y );
}
Run Code Online (Sandbox Code Playgroud)

通过以下方式调用:

int x = Apply( 2, 4, add<int> );
Run Code Online (Sandbox Code Playgroud)

  • 我相信他想通过 *add* ** 而没有 ** 指定 *int* 作为模板参数。 (3认同)

Kon*_*lph 5

我有点困惑...为什么你的伪代码中的类型区别?

C++模板允许对模板进行完全类型推导:

template <typename T, typename F>
T function(T x, T y, F op) {
    return op(x, y);
}
Run Code Online (Sandbox Code Playgroud)

在这里,F适合可以使用()函数调用语法调用的任何东西(特别是函数),并且恰好接受两个类型的参数T(或者可以隐式地转换为它).