【发布时间】:2015-10-05 20:40:04
【问题描述】:
我正在开发一个混合类型的 Config Reader 类,它支持从环境、命令行、文件等读取配置数据。
我有点遵循 std::tuple 类型设计:
template <class... Ts> struct ConfigReader {};
template <class T, class... Ts>
class ConfigReader<T, Ts...> : ConfigReader<Ts...>
{
public:
typedef boost::fusion::set<T, Ts...> sequence_type;
ConfigReader(T t, Ts... ts)
: ConfigReader<Ts...>(ts...)
, parameters_(t, ts...)
{
this->init();
}
private:
sequence_type parameters_;
void init()
{
boost::fusion::for_each(parameters_, SetFromEnvironment());
boost::fusion::for_each(parameters_, SetFromCommandLine());
boost::fusion::for_each(parameters_, SetFromConfigFile());
}
};
但我意识到我也可以在没有递归继承的情况下定义它
template <class T, class... Ts>
class ConfigReader<T, Ts...>
{
public:
typedef boost::fusion::set<T, Ts...> sequence_type;
ConfigReader(T t, Ts... ts)
: parameters_(t, ts...)
{
this->init();
}
template <class Type>
typename boost::fusion::result_of::value_at_key<Sequence const, Type>::type get()
{
return boost::fusion::at_key<Type>(parameters);
}
private:
sequence_type parameters_;
void init()
{
boost::fusion::for_each(parameters_, SetFromEnvironment());
boost::fusion::for_each(parameters_, SetFromCommandLine());
boost::fusion::for_each(parameters_, SetFromConfigFile());
}
};
后一种情况似乎效果更好,因为 init() 只被调用一次,这正是我想要的。但是现在我很困惑这两者之间有什么区别?如果没有递归继承,我会失去一些东西吗?
简化用法是......(忽略参数类型结构)
int main()
{
ConfigReader<Start, End, Resources> configReader(Start(), End("infinity"), Resources());
Start startTime = configReader.get<Start>();
}
【问题讨论】:
-
不清楚你在做什么。特别是,您不只是使用
std::tuple有什么原因吗?什么是init(),它在哪里定义? -
我添加了更多信息。但这真的会影响递归继承与非递归继承之间有什么区别的答案吗?
标签: c++ templates c++11 variadic-templates