c++ - 在编译时获取 std::variant 类型

标签 c++ template-meta-programming variant

假设我们在某处定义了:

using mytype_t = std::variant<int, float>;
我想检索 mytype_t 可以存储的所有可能类型.我查了 reference .没有定义我可以使用的成员类型(例如: mytype_t::value_types )。
我正在尝试做这样的事情:
using myvectype_t = std::variant<std::vector<mytype_t::value_types>...>;

最佳答案

你不需要一个特殊的成员,因为信息就在类型中:

#include <variant>
#include <iostream>
#include <vector>
#include <type_traits>

template <typename T>
struct foo;

template <typename...V>
struct foo< std::variant<V...>> {
    using type = std::variant<  std::vector<V> ...>;
};


int main() {
    using vari = std::variant<int,double>;
    using varivect = std::variant< std::vector<int>, std::vector<double>>;
    std::cout << std::is_same<foo<vari>::type,varivect>::value;
}
输出:
1
Live example

关于c++ - 在编译时获取 std::variant 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63114181/

相关文章:

c++ - 如何检测类型是否为通用类型列表之一

c++ - boost::variant 和 void* 指针

c++ - 在 C 中输入具有 "boolean"返回类型和 "no parameters"的函数

c++ - 向线程发送消息?

c++ - 不完整类型 boost function_traits 的无效使用

c++ - 构造 std::tuple 类型的索引数组

c++ - 使用 lambda 和定点组合器递归访问 `std::variant`

c++ - 嵌套变体的简洁初始化语法?

c++ - 使用相同种子在代码的不同部分生成 C++-11 中的随机数

c++ - 模板参数中是否禁止使用 SFINAE,还是我遇到了 clang 错误?