将 std::plus 作为参数传递

passing std::plus as an argument

如何将 std::plus 作为函数参数传递?

#include<functional>
#include<iostream>

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

template<class T>
struct X
{
    template < typename F>
    T foo(T a, T b, F f)
    {
        return fn<T, F>(a,b,f);
    }
};

int main()
{
    int a = 1;
    int b = 1;
    X<int> f;
    std::cout<< f.foo(a,b, std::plus<int>);
    return 0;
}

https://onlinegdb.com/g5NZc2x9V

main.cpp:7:21: 错误:')' 标记前的预期主表达式

std::plus<int> 是一种类型,而不是对象或函数。所以你不能把它传递给一个函数。但是,您可以创建该类型的对象并传递它:

std::cout<< f.foo(a,b, std::plus<int>{});

然后在通话中

return f<T>()(a,b);

模板参数和第一个 () 没有意义。 f 不是模板,它是一个对象,您要调用其 operator(),所以:

return f(a,b);
std::cout<< f.foo(a,b, std::plus<int>);

std::plus<int> 是一种类型。就像 int。失败的原因与以下代码也无法编译的原因完全相同:

void function(int n)
{
}

void another_function()
{
    function(int);
}

您不能“将 std::plus 作为参数传递”,原因与您不能将 int 作为参数传递一样。

不过,您可以做的——以及您应该做的——是构造一个实例 of std::plus:

std::cout<< f.foo(a,b, std::plus<int>{});

现在,这会将一个实际对象 std::plus<int> 传递给此函数。然而,这还不够:

T fn(T a, T b, F f)
{
        return f<T>()(a,b);
}

在这里,f 将成为 std::plus<int> 对象。它是一个可调用对象,所以,你所要做的就是调用它:

T fn(T a, T b, F f)
{
        return f(a,b);
}

如果您想将 std::plus 作为运行时参数传递,您必须实际构造一个。

您不能将类型作为参数传递。尝试传递一个裸 std::plus<int> 类似于在那里写一个 class 名称或类型名称,即如果 foo(a,b, int) 期望第三个参数是一个 int [=18],你不会期望编译=]值.

#include <functional>
#include <iostream>

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

template<class T>
struct X
{
    template < typename F>
    T foo(T a, T b, F f)
    {
        return fn<T, F>(a, b, f);
    }
};

int main()
{
    int a = 1;
    int b = 1;
    X<int> f;
    std::cout << f.foo(a, b, std::plus<int>());
    return 0;
}