【发布时间】:2017-06-10 18:16:09
【问题描述】:
可以理解,函数不能既是模板化的又是虚拟的。 但是可能有一种超级智能的设计模式可以做到。
我的目标是有一个看起来像这样的函数:
void configure(const Configuration &config){
double stuff = config.get<double>("stuff");
int thing = config.get<int>("thing");
// rest of the code
}
理想情况下,我可以传递各种配置对象,例如从文件或数据库中读取的对象。
这是一个使用 yaml-cpp 的具体配置类的(精简到最低限度)示例(我想即使你不知道 yaml-cpp 也可以理解):
class YAML_config : public Configuration {
public:
YAML_config(std::string file_path){
this->node = YAML::LoadFile(file_path);
}
template<typename T> T get(std::string key){
return this->node[key].as<T>();
}
private:
YAML::Node node;
问题是:什么是适合类 Configuration 的代码?
这里有一些显示意图的无效代码:
class Configuration {
virtual template<typename T> T get(std::string key)=0;
}
如果这一切只是一个糟糕的开始,我应该考虑其他任何方法吗?我检查了“类型擦除”,但这似乎没有帮助(或者我错过了什么?)
【问题讨论】:
-
您可能有一个受保护的非模板虚函数,它返回一个
boost::any,然后将get模板函数设为非虚函数并在那里执行转换? -
与问题完全无关......但是你为什么要传入 shared_ptr?
-
@TartanLlama 听起来很有希望......你有没有机会详细说明:)?
-
@rubenvb 指针的所有优点没有缺点...
-
@Vince 这句话总结了使用 shared_ptr 的所有错误原因。据我所知,这个函数没有参数的所有权。如果参数超过函数调用,只需通过 (const) ref 传递它。无需开销即可获得 C++ 的所有优点。
标签: c++ templates polymorphism virtual type-erasure