我想编写一个基于以下不同输入返回不同类型的函数。
enum MyType
{
A,
B
};
template<MyType T> struct MyStruct
{
};
static auto createMyStruct(MyType t)
{
if(t==A)
return MyStruct<A>();
else
return MyStruct<B>();
}
无法解决问题,因为一种汽车有两种返回类型。还有其他方法吗?
最佳答案
绝对不可能有一个(单个)函数根据运行时决策返回不同的类型。在编译时必须知道返回类型。但是,您可以使用这样的模板函数(由于@dyp使我简化了代码):
#include <iostream>
#include <typeinfo>
enum MyType
{
A,
B
};
template<MyType>
struct MyStruct {};
template<MyType type>
MyStruct<type> createMyStruct()
{
return {};
}
int main()
{
auto structA = createMyStruct<A>();
auto structB = createMyStruct<B>();
std::cout << typeid(structA).name() << std::endl;
std::cout << typeid(structB).name() << std::endl;
}