简体   繁体   English

C ++如何在编译时检查变量映射的类型

[英]C++ How to check the type of a variant map at compile time

I would like to have a map of key, value pairs; 我想要一张键,值对的地图; the keys can be implemented as string or enum class; 键可以实现为字符串或枚举类; but the values need to support multiple types, eg int or bool 但是这些值需要支持多种类型,例如intbool

Now, I would want to have a function with the following signature 现在,我想要一个带有以下签名的函数

template<typename T>
void getOption(KeyClass key_, T& value_)

Given that the map will be constant, is it possible to make the function checking the type at compile time? 鉴于映射将是恒定的,是否有可能使函数在编译时检查类型?

For example, if the map is something like {"start_time": 2, "can_abort": false} 例如,如果地图类似于{“ start_time”:2,“ can_abort”:false}

There should be a compilation error on 上应该有编译错误

bool can_abort;
getOption("start_time", can_abort);

If you can use enum values for your keys, and the types and values are known at compile-time, why not just have a plain struct? 如果您可以将枚举值用作键,并且类型和值在编译时是已知的,那么为什么不只具有普通结构呢?

struct options_t {
    int start_time;
    bool can_abort;
};

If you really must iterate over elements of different types, you can go full voodoo and use Louis Dionne's Boost.Hana library. 如果您真的必须遍历不同类型的元素,则可以使用完全伏都教并使用Louis Dionne的Boost.Hana库。 It has a multi-type map class . 它具有一个多类型的地图类 Everything will be checked at compile time. 一切都将在编译时检查。

Alternatively, if you want more run-time-oriented behavior, and you want flexibility wrt the types you stick in your map, you could use type erasure and make it, say, an std::unordered_map<std::string, std::any> . 另外,如果您想要更多的面向运行时的行为,并且希望灵活地添加到映射中的类型,则可以使用类型擦除并将其设置为std::unordered_map<std::string, std::any> The std::any type holds, well, a value of any type; std::any类型可以保存std::any类型的值; but it is up to you to know which type to try and extract from it (if you're wrong you get an exception) - ie you won't have compile time checking. 但是由您决定尝试尝试从中提取哪种类型(如果输入错了,则会得到异常)-即,您将没有编译时间检查。

As for using a variant - you can use those, but if your keys are std::string s, then nothing is going to be checked at compile time, as std::string s involve heap allocation. 至于使用变体-您可以使用它们,但是如果您的键是std::string ,那么在编译时将不会检查任何内容,因为std::string涉及堆分配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM