在编译时从变量获取类型

时间:2019-03-26 00:18:32

标签: c++ c++11 templates variant

我需要对变量类型在编译时是否可以容纳类型进行类型检查。

我正在将枚举和字符串转换为变量,但是我希望库与用户提供的变量兼容(针对它们支持的类型)。因此,我有一个模板参数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;
}

2 个答案:

答案 0 :(得分: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 :(得分: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); }

注意,不是专长。只是超载。