函数调用中多于一个圆括号?

More than one round bracket in function call?

我有一个练习需要编写一个函数。功能方案看起来像

auto add(int a){
}

我需要能够调用带有多个括号的函数:

add(1)(2)(3); // 6
add(1)(2)(3)(4); // 10
add(1)(2)(3)(4)(5); // 15

但我不知道在这种情况下应该使用哪个 C++ 功能。我听说我应该使用函子,但我不知道在这种情况下这是否是最好的主意。

我想到的唯一解决方案是将此 "add" 作为一些 class 带有重载括号运算符的对象,这将 return 新对象,然后从中调用新括号它,但是你需要以某种方式从它 return 最终值,比如一些 getter func.

class Adder{

private:
    int value;
public:
    Adder():value(0){}
    Adder(int a):value(a){}
    int get(){return value;}
    Adder operator() (int a) {
        return Adder(value+a);
    }
};

不过好像没什么用,可能有更好的方法可以达到你想要的效果。

你可以通过 add return 一个 functor, i.e., an object that implements operator(). You can write a templated version that will let the compiler deduce the type. Try it here.

template <class T>
struct adder 
{
    T val;

    adder(T a) : val(a) {}

    template <class T2>
    auto operator()(T2 a) -> adder<decltype(val + a)> { return val + a; }

    operator T() const { return val; }
};

template <class T>
adder<T> add(T a)
{
    return a;
}

例子

在此示例中,T 最终将解析为 double:

std::cout << add(1)(2.5)(3.1f)(4) << std::endl;
// T is int -----^
// T is double ------^
// T is still double -----^
// T is still double ----------^

这是另一个示例,其中 T 将解析为 double:

std::cout << add(1)(2.5f)(3.1)(4) << std::endl;
// T is int -----^
// T is float -------^
// T is double ------------^
// T is still double ----------^

显式构造函数

如果您希望 adder 的构造函数是 explicit 您还必须稍微更改 return 语句。

template <class T>
struct adder 
{
    T val;

    explicit adder(T a) : val(a) {}

    template <class T2>
    auto operator()(T2 a) -> adder<decltype(val + a)>
    {
        return adder<decltype(val + a)>(val + a);
    }

    operator T() const { return val; }
};

template <class T>
adder<T> add(T a)
{
    return adder<T>(a);
}