【发布时间】:2013-06-19 19:00:22
【问题描述】:
我正在尝试声明许多从Base 继承的模板化Derived<T> 对象,并将它们推回std::vector<Base*>。
struct Base { ... };
template<typename T> struct Derived : Base { /* ctor(const string&) */ ... }
Derived<bool> online{"online"};
Derived<bool> official{"official"};
Derived<bool> noRotation{"no_rotation"};
Derived<bool> noBackground{"no_background"};
Derived<int> noSound{"no_sound"};
Derived<string> noMusic{"no_music"};
Derived<bool> blackAndWhite{"black_and_white"};
vector<Base*> configValues{&online,
&official,
&noRotation,
&noBackground,
&noSound,
&noMusic,
&blackAndWhite};
如您所见,代码很糟糕。有没有办法在不将vector 作为const& 传递给Derived<T>::Derived<T>(...) 构造函数的情况下自动执行此操作?
自动化是指避免对象名称的重复。我想用我所有的Derived<T> 对象填充std::vector,而不必手动列出它们。
(宏已接受,但希望有更好的解决方案)
【问题讨论】:
-
你能用
std::vector<Derived<bool>>代替吗? -
“自动化”是什么意思?
-
@justin:
T在我的应用程序中并不总是bool。对不起,这个例子没有显示出来。 @tmpearce:我的意思是避免重复对象名称。我想用我所有的Derived<T>对象填充一个向量,而不必手动列出它们。 -
@CaptainObvlious 完成。
-
你想完成什么?看来您可能对
boost::any感兴趣。
标签: c++ templates inheritance c++11 vector