如何根据枚举参数返回不同的类型

yeh*_*ehi 3 c++ templates sfinae stdany std-variant

我有两个需要以下功能的功能:

功能1:需要变量的地址来设置值。(它知道正确的类型)

函数2:是一个需要类型值的重载函数。

我需要一种基于枚举(指定要使用的类型)返回不同类型的方法。

我尝试使用 std::get 因为您可以使用数字来指定类型。然而,它要求 SelectedType 是一个常量表达式,但事实并非如此。

std::variant<uint8_t,int8_t,uint16_t,int16_t,double,float> Var;
std::get<SelectedTypeEnum>(Var)
Run Code Online (Sandbox Code Playgroud)

要点是使用一个变量来避免代码重复。

考虑以下代码:

enum Type{
Type_uint8_t,
Type_int8_t,
Type_uint16_t,
Type_int16_t,
Type_std::string
} TypeList;

GetTypeToUse(Type&){ /* Get/Set the type to use */ }

void SetValueBasedOnEnum(Type TypeToUse,void* ptr) {/* Function 1: Sets the value of the type */}

// This is a  Overloaded Function which supports all types in the enum. 
//"T" represents the type.
void DoStuffWithDifferentTypes(T ValueOfType) { /*Function 2:*/ }



Run Code Online (Sandbox Code Playgroud)

Nat*_*ica 5

您不能根据传递给函数的枚举值返回不同的类型。函数签名是在编译时设置的,因此任何会改变它的东西都必须是编译时构造。

如果您必须返回只能在运行时知道的不同类型,那么您可以使用std::variantorstd::any来实现。 std::variant基本上是一个标记联合,因此您必须指定它可以容纳哪些类型。如果您有一组有界的类型,那么这是首选的数据结构。如果您有无限的类型集,那么您可以使用std::any. 它使用类型擦除和动态内存分配,因此使用起来比 a 贵得多,std::variant但这就是您获得无限灵活性所必须付出的成本。

如果对您的用例有意义,另一种选择是让所有类型都继承自公共基类型。然后,您可以从函数返回指向基类的指针,但可以多态地处理该对象。