我想知道,是否有可能在 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/