在 C++ 中,有没有办法根据输入类是否抽象来定义模板行为?

背景:我继承了一个大型系统,该系统使用模板来存储有关类的元数据,这可能会影响这个问题中固有的一些假设。

我正在使用一个模板注册系统,该系统部分基于此处找到的答案:是否有办法从包含类名的字符串中实例化对象?. 宏在我的系统中是行不通的,boost(或任何第三方 API)的使用也是如此。

问题:我是否可以根据输入类型是抽象的还是具体的而使模板的行为有所不同?

我正在寻找这样的东西(此处使用的代码直接从链接问题中接受的答案中复制而来):

struct BaseFactory {
    typedef std::map<std::string, Base*(*)()> map_type;

    static Base * createInstance(std::string const& s) {
        map_type::iterator it = getMap()->find(s);
        if(it == getMap()->end())
            return 0;
        return it->second();
    }
protected:
    static map_type * getMap() {
        // never delete'ed. (exist until program termination)
        // because we can't guarantee correct destruction order 
        if(!map) { map = new map_type; } 
        return map; 
    }

private:
    static map_type * map;
};

template<typename T>
struct DerivedRegister : BaseFactory { 
    DerivedRegister(std::string const& s) { 
        getMap()->insert(std::make_pair(s, &createT<T>));
    }
};

// in derivedb.hpp
class DerivedB {
    ...;
private:
    static DerivedRegister<DerivedB> reg;
};

// in derivedb.cpp:
DerivedRegister<DerivedB> DerivedB::reg("DerivedB");

除了我希望 DerivedRegister 根据 T 是抽象还是具体而表现不同。在 T 是抽象的情况下,我希望 DerivedRegister 不会在映射中注册该类型。

正如我在背景中提到的,我已经继承了一个已经存在于类层次结构(抽象或具体)中的现有系统。修改这个现有系统以添加地图注册是微不足道的;然而,抽象类会导致问题,因为对它们调用 new 是无效的。

在 BaseFactory 和 DerivedRegister 之间添加额外的继承和模板层不会有问题;但是, DerivedRegister 已经存在于每个类中,我无法更改它。

我认识到我可以添加一个独立于现有模板类的唯一注册系统,并且只将其添加到具体类中。我特别询问是否有解决方案可以在不使用第三方库的情况下在 C++11 中避免这种情况(我知道很多限制......)。

回答

使用std::is_abstract


以上是在 C++ 中,有没有办法根据输入类是否抽象来定义模板行为?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>