我正在尝试制作一个配置管理器类,它可以通过 std::string 存储任意对象。
我对我的接口(interface)(抽象基类)的最初想法是这样的(当然这是非常不完整的)
class ConfigurationManager
{
public:
static boost::shared_ptr<ConfigurationManager> create();
template<typename T>
virtual T getOption(const std::string& name) = 0;
};
但后来我的编译器指出模板不能是虚拟的(然后我意识到无论如何我都不能导出模板)。
我将在内部使用 boost::any(几乎是运行时检查无效*),但我不想在我的界面中公开 boost::any。
解决此问题的最佳方法是什么?
最佳答案
创建一个返回 boost::any
的 protected 虚拟抽象函数,以及一个非虚拟的、非抽象的公共(public)模板函数,以对您的界面用户隐藏它。
class ConfigurationManager {
protected:
virtual boost::any getOptionProtected(const std::string& name) = 0;
public:
static boost::shared_ptr<ConfigurationManager> create();
template<typename T> T getOption(const std::string& name) {
return boost::any_cast<T>(getOptionProtected(name));
}
};
关于c++ - 有什么方法可以在抽象基类中使用模板函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8611318/