首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >初始化C++模板的静态数据成员

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

Stack Overflow用户
提问于 2014-04-24 12:51:37
回答 1查看 41关注 0票数 0

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

代码语言:javascript
复制
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;

};

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

代码语言:javascript
复制
std::transform(prices.begin(),prices.end(),prices.begin(),std::bind(VAT<double,double>(25),std::placeholders::_1));

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

代码语言:javascript
复制
P operator()(C currency ){
        currency = currency + currency * (percentance/100);
            sum = sum + currency;
        return currency;
    }

但这是不正确的。有什么办法可以实现我想做的事情吗?

EN

回答 1

Stack Overflow用户

发布于 2014-04-24 13:00:02

你可以,只要稍微调整一下你的类和你使用它的方式。

代码语言:javascript
复制
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;
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23260099

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档