혼동? 나 너무 ... 는 다음생성자 이니셜 라이저 목록의 구성원이 아닌 초기화
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;
}
};
이지만, 하나의 ThresholdSensor::CommonData
에서지도를 초기화하기 위해 어떤 방법이 있음 생성자 init 동안 믹스의 즉,지도를 참조하여 전달할 수 있으며, 믹스 인 생성자에서 초기화 할 수 있습니까?
참 true 고정 – nass
이 코드에서는'MapInitializer'가 완전히 불필요하다는 것을 알고 있습니까? 'initializer_list' 만 사용하십시오 –
@MooingDuck 더 나은, 브레이싱 된 이니셜 라이저 사용 –