在编写一些库绑定代码时,我尝试定义基于数组的类型,遇到了一个奇怪的挑战。
考虑如下的枚举:
enum class MyTypes
{
UInt,
Int,
Float
}
利用某些类型特征,我可以将枚举值转换为类型:
template <MyTypes Ty> struct typeify;
template <> struct typeify<MyTypes::UInt> { using type = unsigned int; };
template <> struct typeify<MyTypes::Int> { using type = int; };
template <> struct typeify<MyTypes::Float> { using type = float; };
template <MyTypes Ty> using typeify_t = typename typeify<Ty>::type;
为了帮助绑定,我还有这个(因为 C++ 没有反射):
inline static constexpr std::array KnownTypes
{
std::pair{"UInt", MyTypes::UInt},
std::pair{"Int", MyTypes::Int},
std::pair{"Float", MyTypes::Float}
};
从这里,我想std::variant
根据已知的类型定义一个。
有了 3 个值,显然只需像这样写出变量:
std::variant<unsigned int, int, float>
std::variant
但在我的情况中,我有 50 多种类型。因此,我希望有一种方法可以从数组KnownTypes
和类型特征中自动生成类型定义typeify_t
。
我认为我已经接近以下内容,但由于无法为可变模板参数提供默认值,我受到了困扰:
template <template <typename T, T ... Idx> class temp = std::make_index_sequence<KnownTypes.size()>>
using AnyKnownType = std::variant<typeify_t<KnownTypes[Idx].second>, ...>;