在抽象基类中具有模板功能的任何方法? [英] Any way to have a template function in an abstract base class?

查看:70
本文介绍了在抽象基类中具有模板功能的任何方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个配置管理器类,该类可以通过std :: string存储任意对象。

I am trying to make a configuration manager class, that can store arbitrary objects by std::string.

我的界面设计初衷(抽象基类)是这个(当然这是非常不完整的)

My starting idea for my interface (abstract base class) was this (of course this is horribly incomplete)

class ConfigurationManager
{
public:
   static boost::shared_ptr<ConfigurationManager> create();

   template<typename T>
   virtual T getOption(const std::string& name) = 0;
};

但是后来我的编译器指出模板不能是虚拟的(然后我意识到我不能导出

But then my compiler pointed out that template's cannot be virtual(and then I realized that I cannot have exported templates anyways).

内部,我将使用boost :: any's(几乎是运行时检查过的void *),但我不想公开boost :::在我的界面中。

Internally I am going to be using boost::any's(pretty much a runtime checked void*), but I do not want to expose boost::any in my interface.

什么是最好的解决方法?

What would be the best way to go about this?

推荐答案

创建一个受保护的虚拟抽象函数,该函数返回 boost :: any ,以及一个非虚拟,非抽象的公共模板函数,将其隐藏在界面的用户中。 / p>

Make a protected virtual abstract function returning boost::any, and a non-virtual, non-abstract, public template function to hide it from the users of your interface.

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));
    }
};

这篇关于在抽象基类中具有模板功能的任何方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆