gpt4 book ai didi

C++:编译未使用的类

转载 作者:行者123 更新时间:2023-11-30 01:21:53 26 4
gpt4 key购买 nike

我喜欢使用如下模式来实现工厂类(摘 self 对 this 问题的回答):

class Factory
{
public:
template<class DerivedType>
DerivedType::CreatedType *createType()
{
DerivedType::CreatedType *r = (DerivedType::CreatedType) (*(m_creators[DerivedType::id]))();
return r;
}
protected:
static std::map<int,void *(*)()> m_creators;
};

std::map<int,void *(*)()> Factory::m_creators = std::map<int,void*(*)()>();

template<class Derived, class CreatedType>
class CRTPFactory : public Factory
{
typedef typename CreatedType CreatedType;
public:
static bool register()
{
Factory::m_creators.push_back(std::make_pair(Derived::id,Derived::create);
return true;
}

private:
static bool m_temp;
};

template<class Derived>
bool CRTPFactory<Derived>::m_temp = CRTPFactory<Derived>::register();

class AFactory : public CRTPFactory<AFactory,A>
{
private:
static A *create()
{
//do all initialization stuff here
return new A;
}

public:
static const int id = 0;
};

这允许在无需更改工厂类的情况下为新类型扩展工厂。它还允许为不同类型实现特定的创建算法,而无需更改工厂类。但是这种模式有一个主要问题。类 AFactory 从未被显式使用。它在加载时通​​过 CRTPFactory 的成员 temp 注册它的创建者函数。这可能有点难以理解,但它非常容易使用。问题是 AFactory 未编译,因此它的静态参数未在加载时初始化。我的问题是,是否可以强制编译器(我使用的是 VS 2012,但 GCC 的答案也很好)编译 AFactory 而无需显式创建它的实例?我在 VS 中使用的一个解决方案是 dllexport AFactory,这样编译器会编译类,即使它不知道任何人实例化它。这是因为它假定其他一些 dll 可能会实例化它。此解决方案的问题在于工厂类必须与其余代码一样在单独的 dll 中实现。而且这在 GCC 上也不起作用。

最佳答案

继承自 CRTPFactory<AFactory,A>导致类的隐式实例化,而不是其成员的定义。

[temp.inst]

The implicit instantiation of a class template specialization causes the implicit instantiation of the declarations, but not of the definitions or default arguments, of the class member functions, member classes, static data members and member templates;

而不是继承自CRTPFactory<AFactory,A> ,您可以简单地显式实例化 m_temp成员(member)。

template bool CRTPFactory<AFactory,A>::m_temp;

作为引用,这里是修改后的示例(以编译的形式):

#include <map>

class Factory
{
public:
template<class DerivedType, class CreatedType>
CreatedType *createType()
{
CreatedType *r = (CreatedType) (*(m_creators[DerivedType::id]))();
return r;
}
protected:
static std::map<int,void *(*)()> m_creators;
};

std::map<int,void *(*)()> Factory::m_creators = std::map<int,void*(*)()>();

template<class Derived, class CreatedType>
class CRTPFactory : public Factory
{

public:
static bool register_()
{
Factory::m_creators.insert(std::make_pair(Derived::id,Derived::create));
return true;
}

static bool m_temp;
};

template<class Derived, class CreatedType>
bool CRTPFactory<Derived, CreatedType>::m_temp = CRTPFactory<Derived, CreatedType>::register_();

struct A
{
};

class AFactory
{
public:
static void *create()
{
//do all initialization stuff here
return new A;
}

public:
static const int id = 0;
};

template bool CRTPFactory<AFactory,A>::m_temp;

关于C++:编译未使用的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17466466/

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