operator作为模板参数

时间:2010-09-17 12:45:10

标签: c++ templates operators

有可能吗?

template<operator Op> int Calc(int a, b)
{ return a Op b; }

int main()
{ cout << Calc<+>(5,3); }

如果没有,是否可以在没有ifs和开关的情况下实现这一目标?

5 个答案:

答案 0 :(得分:19)

您可以使用仿函数:

template<typename Op> int Calc(int a, int b)
{
    Op o;
    return o(a, b);
}

Calc<std::plus<int>>(5, 3);

答案 1 :(得分:17)

否 - 模板是关于类型原始值

你仍然可以传递所谓的函数对象,它们可以像函数一样调用并带有所需的运算符功能(尽管语法很好)。

标准库定义了几个,例如: std::plus添加......

#include <functional>

template<typename Op>
int Calc(int a, int b, Op f) { 
  return f(a, b);
}

int main() { 
  cout << Calc(5,3, std::plus());
  cout << Calc(5,3, std::minus());
}

答案 2 :(得分:2)

您可以使用多态:

#include <cstdlib>
#include <iostream>
using namespace std;


class Operator
{
public:
    virtual int operator()(int a, int b) const = 0;
};

class Add : public Operator
{
public:
    int operator()(int a, int b) const
    {
        return a+b;
    }
};

class Sub : public Operator
{
public:
    int operator()(int a, int b) const
    {
        return a-b;
    }
};

class Mul : public Operator
{
public:
    int operator()(int a, int b) const
    {
        return a*b;
    }
};


int main()
{
    Add adder;
    cout << adder(1,2) << endl;
    Sub suber;
    cout << suber(1,2) << endl;
    Mul muler;
    cout << muler(1,2) << endl;
    return 0;
}

答案 3 :(得分:0)

如果您参考全球运营商,您已经收到了一些答案。但是,在某些特定情况下,使用重载的运算符函数也可能会有所帮助。

这可能是微不足道的;尽管如此,在某些情况下它可能会有所帮助,这就是我发布一个例子的原因:

2
20

输出:

apt-get install screen

# Create a session called "my_app"
screen -S my_app

# Now you are inside another shell
xvfb-run npm start

# After that, you can detach the screen or close the connection

答案 4 :(得分:0)

使用

template<typename Op>
int Calc(int a, int b, Op f) {
    return f(a, b);
}

int
main() {
    cout << Calc(5, 3, std::plus{});
    cout << Calc(5, 3, std::minus{});
}

如果Dario回答失败,请error: cannot deduce template arguments for ‘plus’ from ()

相关问题