c++ - 在 C++0x 中创建静态类型变体

标签 c++ c++11 variant template-meta-programming

我想知道,是否有可能在 C++0x 中创建一个静态类型的变体,(其行为类似于 auto):

variant<int, bool, std::string> v = 45;

当我们将 v 赋给 int 以外的值时,它不会编译:

v = true; //Compile error

到目前为止我还没有找到任何优雅的解决方案。

最佳答案

这段代码在我的机器上使用 Boost.Variant 和 g++ 4.5 为 C++98 和 C++0x 编译。你想自己实现一个变体类型吗?然后您可能会研究 Boost 实现。

如果您想/get/上述行为,您可以这样做:

auto v = 45;
static_assert(std::is_same<decltype(v), bool>
              || std::is_same<decltype(v), int>
              || std::is_same<decltype(v), std::string>,
              "v must be int, bool or string");

这应该与您描述的完全相同。

以下实现克林顿的建议:

template <typename T, typename... Args>
struct has_type;

template <typename T, typename Head, typename... Args>
struct has_type<T, Head, Args...>
{
    static const bool value = std::is_same<T, Head>::value
                              || has_type<T, Args...>::value;
};

template <typename T>
struct has_type<T> : std::false_type
{};

template <typename... Args, typename T>
T&& check_type (T&& t)
{
    static_assert(has_type<T, Args...>::value, "check_type");
    return std::move(t);
}

你只需要<memory><type_traits>为此,并获得完美的转发和整数提升的正确行为。

关于c++ - 在 C++0x 中创建静态类型变体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5388412/

相关文章:

c++ - VS2010自定义生成.h文件的构建工具

c++ - 实现从一个类到另一个类的类型转换

c++ - 非依赖名称查找和 lambda

types - 将多个变体合并为一个变体

c++ - 带有包含变体的 vector 的 Remove_if

generics - 当从一个泛型映射到另一个泛型时,为什么我必须破坏和重建泛型枚举的非泛型变体?

c++ - 指向非 union 类的指针的大小可以不同吗?

c++ - 程序在构造函数期间崩溃

c++ - 是否有任何理由不使用异常来测试 std::map 中是否存在元素

c++ - strlen() 编译时优化