我有一个类工厂,我在其中为 c'tor 参数使用可变参数模板(下面的代码)。但是,当我尝试使用它时,出现编译错误;当我最初不带参数编写它时,它运行良好。
这是类:
template< class Base, typename KeyType, class... Args >
class GenericFactory
{
public:
GenericFactory(const GenericFactory&) = delete;
GenericFactory &operator=(const GenericFactory&) = delete;
typedef Base* (*FactFunType)(Args...);
template <class Derived>
static void Register(const KeyType &key, FactFunType fn)
{
FnList[key] = fn;
}
static Base* Create(const KeyType &key, Args... args)
{
auto iter = FnList.find(key);
if (iter == FnList.end())
return 0;
else
return (iter->second)(args...);
}
static GenericFactory &Instance() { static GenericFactory gf; return gf; }
private:
GenericFactory() = default;
typedef std::unordered_map<KeyType, FactFunType> FnMap;
static FnMap FnList;
};
template <class B, class D, typename KeyType, class... Args>
class RegisterClass
{
public:
RegisterClass(const KeyType &key)
{
GenericFactory<B, KeyType, Args...>::Instance().Register(key, FactFn);
}
static B *FactFn(Args... args)
{
return new D(args...);
}
};
这是错误:调用时(例如)
// Tucked out of the way
RegisterClass<DataMap, PDColumnMap, int, void *> RC_CT_PD(0);
GCC 4.5.0 给我:
In constructor 'RegisterClass<B, D, KeyType, Args>::RegisterClass(const KeyType&) [with B = DataMap, D = PDColumnMap, KeyType = int, Args = {void*}]':
no matching function for call to 'GenericFactory<DataMap, int, void*>::Register(const int&, DataMap* (&)(void*))'
我不明白为什么它不能编译,在大量谷歌搜索后我找不到答案。谁能告诉我我做错了什么(除了奇怪的变量名,这在上下文中是有意义的)?
最佳答案
我认为它在这里呕吐:
template <class Derived>
static void Register(const KeyType &key, FactFunType fn)
{
FnList[key] = fn;
}
你不使用 Derived
在这个函数中,但它可能搞砸了 gcc 试图解析 GenericFactory<...>.Register(...)
的尝试.您可能还想将其更改为 GenericFactory<...>::Register(...)
.
关于具有可变参数模板问题的 C++0x 类工厂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2906638/