小编yeh*_*ehi的帖子

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

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

功能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)

c++ templates sfinae stdany std-variant

3
推荐指数
1
解决办法
2353
查看次数

标签 统计

c++ ×1

sfinae ×1

std-variant ×1

stdany ×1

templates ×1