有人会如何为模板类实现工厂函数?要么我的谷歌搜索没有找到正确的东西,要么我误解了结果。举个例子:
template<typename T>
class Test
{
public:
T data;
void SizeOfData() { std::cout << "Data Size:" << sizeof(data) << "\n"; }
};
----this what I am trying to figure out how to do------
template <typename T>
Test<T> FactoryFunction(const std::string& type)
{
if(type == "int")
return Test<int>;
if(type == "long")
return Test<long long>;
}
----------------------------------------
int main()
{
auto a = FactoryFunction(std::string("int"));
auto b = FactoryFunction(std::string("long"));
a.SizeOfData();
b.SizeOfData();
a.data = 1;
b.data = 2;
}
显然,这段代码都是错误的——我只是想在理论上展示我想要做什么。可以做到吗?我在 google 中查找什么 - 返回模板类的工厂函数?我什至不知道从哪里开始。如果有人甚至可以为我指明一个方向 - 我真的只想要一个函数,它根据开关或 if/else 列表的结果返回正确的模板实例化。我认为从概念上讲这个想法并不难,但实施它是另一回事 - 或者我真的错过了一些东西。
谢谢你的帮助。
模板化函数的类型 T 必须在编译时确定。因此,您不能按照您提到的方式进行操作。
但是 - 您可以使用以下模式来实现类似的结果:
#include <assert.h>
class TestBase
{
public:
virtual void SizeOfData() = 0;
};
template<typename T>
class Test : public TestBase
{
public:
T data;
virtual void SizeOfData() override { std::cout << "Data Size:" << sizeof(data) << "\n"; }
};
std::unique_ptr<TestBase> FactoryFunction(const std::string& type)
{
if (type == "int")
return std::make_unique<Test<int>>();
if (type == "long")
return std::make_unique<Test<long long>>();
return nullptr;
}
int main()
{
auto a = FactoryFunction(std::string("int"));
assert(a);
auto b = FactoryFunction(std::string("long"));
assert(b);
a->SizeOfData();
b->SizeOfData();
return 0;
}
一些注意事项:
Test 的每个实例(其中 T 发生变化)都是不同的不相关类。为了在它们之间建立连接,我添加了一个公共基类。
为了使用多态性,您必须使用引用语义。因此工厂返回一个指针(在本例中为 a std::unique_ptr
)。
您需要在所有 Test 对象上调用的通用方法 ( SizeOfData
) 变成了基类中的虚拟方法。
这种技术实际上与评论中提到的类型擦除习语有关。
更新:根据下面的评论,我将使用裸new
s替换为std::make_unique
. 您可以在此处查看为什么它更好的更多信息:std::make_unique 和 std::unique_ptr 与 new 之间的差异
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句