gpt4 book ai didi

c++ - 模板类中的静态模板函数

转载 作者:太空宇宙 更新时间:2023-11-04 13:01:44 24 4
gpt4 key购买 nike

这里我们有两个模板类。

第一个名为“Factory”,它不是一个单例工厂模型类,并且有一个模板成员函数负责在这个工厂中注册类生产者。

第二个名为“FactoryRegister”,它唯一的职责是在工厂 T1 中注册 T2。

最后,我们有一个声明 FactoryRegister 变量的宏,通过在全局范围内使用这个宏,我们实现了在我们的程序运行之前注册工厂中的所有类。

#include <memory>
#include <mutex>
#include <map>
#include <string>

template <typename Base>
class Factory {
public:

static std::shared_ptr<Factory<Base> > get_instance() {
static std::shared_ptr<Factory> factory;
if (!factory) {
static std::mutex _new_mutex;
std::lock_guard<std::mutex> guard(_new_mutex);
if (!factory) {
factory.reset(new Factory);
}
}

return factory;
}

template <typename Derived,
typename = typename std::enable_if<std::is_base_of<Base, Derived>::value>::type>
void add(std::string pname) {
std::lock_guard<std::mutex> guard(_mutex);
_producers.emplace(pname, [](std::string name) {return new Derived(name);});
}

void del(std::string pname) {
std::lock_guard<std::mutex> guard(_mutex);
_producers.erase(pname);
}

bool is_exist(std::string pname) {
return _producers.find(pname) != _producers.end();
}

std::shared_ptr<Base> create(std::string pname, std::string name) {
std::shared_ptr<Base> ret;
if (is_exist(pname)) {
ret.reset(_producers[pname](name));
}
return ret;
}

private:
Factory() = default;

Factory(const Factory&) = delete;

Factory& operator=(Factory&) = delete;

private:
std::mutex _mutex;
std::map<std::string, std::function<Base*(std::string)> > _producers;
};

template<typename T1, typename T2>
struct FactoryRegister {
FactoryRegister(std::string name) {
Factory<T1>::get_instance()->add<T2>(name);
}
};

#define REGISTER_TO_FACTORY(BaseClass, DerivedClass) \
const FactoryRegister<BaseClass, DerivedClass> \
REGISTER_WITH_##BaseClass_##DerivedClass(#DerivedClass)

代码,编译器(gcc4.8.2)显示如下:

factory.h: In constructor 'FactoryRegister<T1, T2>::FactoryRegister(std::string)':
factory.h:62:44: error: expected primary-expression before '>' token
Factory<T1>::get_instance()->add<T2>(name);

谁能说出原因?

最佳答案

引自 C++'03 标准 14.2/4:

When the name of a member template specialization appears after . or -> in a postfix-expression, or after nested-name-specifier in a qualified-id, and the postfix-expression or qualified-id explicitly depends on a template-parameter (14.6.2), the member template name must be prefixed by the keyword template. Otherwise the name is assumed to name a non-template.

Factory<T1>::get_instance()-> template add<T2>(name);

顺便说一句,一些编译器有特殊模式,可以无错地编译原始代码

关于c++ - 模板类中的静态模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43931734/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com