【发布时间】:2016-09-21 00:35:41
【问题描述】:
困惑?我也是... 考虑以下
typedef std::map<std::string , double> Thresholds;
class Foo
{
public:
Foo( const double & _toxicThres , const double & _zeroThres )
: thresholds
(
MapInitializer<std::string , double>()
.Add("toxic" , _toxicThres)
.Add("zero" , _zeroThres)
)
private:
Thresholds thresholds;
};
以上工作正常并在构造函数的成员初始化列表中初始化std::map。现在考虑一下:
typedef std::map<std::string , double> Thresholds;
struct CommonData
{
Thresholds thresholds;
};
class Foo //a mixin
{
public:
Foo( Thresholds & thresholds , const double & _toxicThres , const double & _zeroThres )
: thresholds
(
MapInitializer<std::string , double>()
.Add("toxic" , _toxicThres)
.Add("zero" , _zeroThres)
)
};
class Bar //another mixin
{
public:
Bar( Thresholds & thresholds , const double & _warningThres , const double & _zeroThres)
: thresholds
(
MapInitializer<std::string , double>()
.Add("warning" , _warningThres)
.Add("zero" , _zeroThres)
)
};
class OtherGasThreshold{/*...*/}; //yet another mixin, etc...
template<typename ThresholdMixin> //Foo , Bar , or others ...
class ThresholdSensor : public ThresholdMixin
{
public:
ThresholdSensor(double val1 , double val2)
: ThresholdMixin(cd.thresholds, val1 , val2)
{}
private:
CommonData cd;
};
注意MapIniializer代码来自here,是
template<class K, class V>
class MapInitializer
{
std::map<K,V> m;
public:
operator std::map<K,V>() const
{
return m;
}
MapInitializer& Add( const K& k, const V& v )
{
m[ k ] = v;
return *this;
}
};
当然,上面的代码不会编译,但是有没有办法在构造函数初始化期间在其中一个 mixin 中初始化 ThresholdSensor::CommonData 中的映射。即我可以通过引用传递地图,在mixins构造函数中初始化它吗?
【问题讨论】:
-
真正真正的固定
-
你知道
MapInitializer对于这段代码是完全没有必要的吗?只需使用initializer_list -
@MooingDuck 更好,使用大括号初始化器
-
@M.M:(在封面下使用
initializer_list) -
@M.M 你能详细说明一下吗?我之前尝试过 `Foo(...):thresholds{ {"toxic",_toxicThres} , { "zero", _zeroThres } } 但它没有用。什么是正确的语法
标签: c++ c++11 initializer-list