在编译时从variant获取类型

问题描述 投票:0回答:2

我需要做一个关于变量类型是否可以在编译时保存类型的类型检查。

我正在将枚举和字符串转换为变体,但我希望该库与用户提供的变体兼容(对于它们支持的类型)。所以我有一个模板参数CustomVariant来表示支持类型的子集AlphaBetaGammaDeltaEpsilon的变体。如果我无法创建有效的变体,我想返回std::nullopt

template <typename CustomVariant>
std::optional<CustomVariant> AsCustomVariant(LargeEnum type, const std::string& name) {
  case LargeEnum::ALPHA:
  case LargeEnum::BETA:
    return ConvertAlphaBeta(name);

  case LargeEnum::GAMMA:
    return ConvertGamma(name);

  case LargeEnum::DELTA:
    return ConvertDelta(name);

  case LargeEnum::EPSILON:
    return ConvertEpsilon(name);

  default:
    return std::nullopt;
}

我的想法是使用某种模板魔术,可以做类似的事情:

if (std::type_can_convert<CustomVariant, Gamma>) {
  return ConvertGamma(name);
} else {
  return std::nullopt;
}
c++ c++11 templates variant
2个回答
2
投票

使用c ++ 17(我知道它用c ++ 11标记),这非常简单 - 你甚至不必真正做任何事情:

#include <variant>
#include <type_traits>
#include <string>

using namespace std;

int main() {

    // this works, as expected
    if constexpr(is_constructible_v<variant<int>, double>) {
        // this will run
    }

    // this is fine - it just won't happen, 
    if constexpr(is_constructible_v<variant<int>, string>) {
        // this won't run
    } else {
        // this will run
    }
    // but obviously the assignment of a string into that variant doesn't work...
    variant<int> vi="asdf"s;
}

https://godbolt.org/z/I-wJU1


1
投票

首先我要这样做:

template<class T>struct tag_t{using type=T;};
template<class T>constexpr tag_t<T> tag{};

template<class...Ts>using one_tag_of=std::variant<tag_t<Ts>...>;

using which_type=one_tag_of<AlphaBeta, Gamma, Delta /* etc */>;

which_type GetType(LargeEnum e){
  switch (e){
    case LargeEnum::Alpha:
    case LargeEnum::Beta: return tag<AlphaBeta>;
    // etc
  }
}

现在我们这样做:

template <typename CustomVariant>
std::optional<CustomVariant> AsCustomVariant(LargeEnum type, const std::string& name) {
  auto which = GetType(type);
  return std::visit( [&name](auto tag)->std::optional<CustomVariant>{
    using type=typename decltype(tag)::type;
    if constexpr (std::is_convertible<CustomVariant, type>{})
      return MakeFromString( tag, name );
    return std::nullopt;
  }, which );
}

这留下了MakeFromString

写这样的重载:

inline Delta MakeFromString(tag_t<Delta>, std::string const& name){ return ConvertDelta(name); }

请注意,不是专业化。只是超载。

© www.soinside.com 2019 - 2024. All rights reserved.