gpt4 book ai didi

c++ - 带有模板的基于枚举的工厂无法转换类型

转载 作者:行者123 更新时间:2023-11-30 02:34:50 24 4
gpt4 key购买 nike

我遇到了一个对我来说有点太大的问题。搜索它是另一个复杂的问题,因为我无法想象到底要搜索什么。所以我希望有人能给我指明正确的方向。

当使用枚举实现工厂以选择作为模板类的变体时,问题就出现了。问题是即使对于不可能的情况,编译器也会执行类型检查。最小示例如下:

template <class T1, class T2>
class Base {
public:
Base() {}
};

template <class T1>
class A : public Base<T1, T1> {
public:
A(): Base<T1, T1>() {}
};

template <class T1, class T2>
class B : public Base<T1, T2> {
public:
B(): Base<T1, T2>() {}
};

enum class Type {
TYPE_A, TYPE_B
};

class Factory {
public:
template<class T1, class T2>
static Base<T1, T2>* Create(Type type) {
switch (type) {
case Type::TYPE_A:
return new A<T1>();
case Type::TYPE_B:
return new B<T1, T2>();
}
return nullptr;
}
};

int main(int argc, char const * argv[]) {
Base<int, double>* ptr = Factory::Create<int, double>(Type::TYPE_B);
delete ptr;
return 0;
}

对于那些你不想运行它的人的错误信息:

test_template_factory.cpp: In instantiation of ‘static Base<T1, T2>* Factory::Create(Type) [with T1 = int; T2 = double]’:
test_template_factory.cpp:38:69: required from here
test_template_factory.cpp:29:26: error: cannot convert ‘A<int>*’ to ‘Base<int, double>*’ in return
return new A<T1>();
^

有解决办法吗?有没有一种方法可以在保持灵 active 的同时避免它?提前致谢!

最佳答案

你应该在编译时选择做什么,而不是在运行时。

这样的事情可以帮助你。

template <class T1, class T2>
class Base {
public:
Base() {}
};

template <class T1>
class A : public Base<T1, T1> {
public:
A(): Base<T1, T1>() {}
};

template <class T1, class T2>
class B : public Base<T1, T2> {
public:
B(): Base<T1, T2>() {}
};

enum class Type {
TYPE_A, TYPE_B
};

class Factory {
public:
template<Type type, class T1, class T2>
static Base<T1, T2>* Create() {
return create_helper<type, T1, T2>::apply();
}
private:
template<Type type, class T1, class T2>
struct create_helper
{
static Base<T1, T2>* apply() { return nullptr; }
};
};

template<class T1, class T2>
struct Factory::create_helper<Type::TYPE_A, T1, T2>
{
static Base<T1, T2>* apply() { return new A<T1>(); }
};

template<class T1, class T2>
struct Factory::create_helper<Type::TYPE_B, T1, T2>
{
static Base<T1, T2>* apply() { return new B<T1, T2>(); }
};


int main(int argc, char const * argv[]) {
Base<int, double>* ptr = Factory::Create<Type::TYPE_B, int, double>();
delete ptr;
return 0;
}

关于c++ - 带有模板的基于枚举的工厂无法转换类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34290743/

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