【发布时间】:2012-08-30 23:20:11
【问题描述】:
我需要定义一个配置对象。我正在使用boost::property_tree 作为 impl,但我不想在我的界面中公开 Impl 详细信息,或者必须在我的界面中使用#include boost 文件。
问题是我想使用ptree的模板方法来获取值,
template <typename T>
T get(const std::string key)
但这是不可能的(?)
// Non compilable code (!)
// Interface
class Config {
public:
template <typename T>
T get(const std::string& key);
}
// Impl
#include "boost/property_tree.h"
class ConfigImpl : public Config {
public:
template <typename T>
T get(const std::string& key) {
return m_ptree.get(key);
}
private:
boost::ptree m_ptree;
}
一种选择是限制我可以“获取”的类型,例如:
// Interface
class Config {
public:
virtual int get(const std::string& key) = 0;
virtual const char* get(const std::string& key) = 0;
}
// Impl
#include "boost/property_tree.h"
class ConfigImpl : public Config {
public:
virtual int get(const std::string& key) { return m_ptree.get<int>(key) };
virtual const char* get(const std::string& key) { return m_ptree.get<const char*>(key); }
private:
boost::ptree m_ptree;
}
但这很丑陋且不可扩展。
还有更好的选择吗?
【问题讨论】:
-
请注意,不能单独对返回类型进行重载,因此第二个代码 sn-p 也不会编译。限制对我来说似乎是合理的,让
get_string()返回一个std::string给调用者,然后调用者可以在必要时将其转换为另一种类型。 -
或者你可以返回一个
boost::any... -
这里有getter的调用语法
m_ptree.get<int>(key),因为你必须以某种方式指定返回值的类型。您不能在自己的代码中使用相同的技术吗?