初始化C ++模板的静态数据成员

时间:2014-04-24 04:51:37

标签: c++

我编写了以下函数对象模板类:

template
<typename P=double, typename C=double>
class VAT{
public:
    VAT(P p):percentance(p){};
    P operator()(C currency ){
        currency = currency + currency * (percentance/100);
        return currency;
    }
private:
    P percentance;

};

将在标准容器上运行并更改其值,例如:

std::transform(prices.begin(),prices.end(),prices.begin(),std::bind(VAT<double,double>(25),std::placeholders::_1));

我想要实现的是sum随着价格的变化而更新。所以我想有一个静态数据成员,所以我重写了包含static C sum = 0

的模板
P operator()(C currency ){
        currency = currency + currency * (percentance/100);
            sum = sum + currency;
        return currency;
    }

但这不正确。无论如何要实现我想做的事情吗?

1 个答案:

答案 0 :(得分:0)

你可以通过对你班级和你使用它的方式进行一些调整。

template <typename P=double, typename C=double>
class VAT{
  public:
    VAT(P p, P& sum):percentance(p), sum(sum) {};
    P operator()(C currency ){
        currency = currency + currency * (percentance/100);
        sum += currency;
        return currency;
    }
  private:
    P percentance;
    p& sum;

};

double sum = 0.0;
VAT<double, double> vat(25, sum);
std::transform(prices.begin(),prices.end(),prices.begin(),vat,std::placeholders::_1));
// Now you can use sum ...
std:cout << sum << std::endl;