c++ - 在编译时从变量中获取类型

标签 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;
}

最佳答案

使用 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

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

相关文章:

c++ - 将按引用传递的变量分配给结构成员时会发生什么

c++ - 在不同的线程上安全地释放资源

javascript - 我的 CSS 有什么问题?

c++ - 在运行时在 C++ 中组合几个类的类

c++ - 员工网络服务框架

c++ - 如果 char 可以在 C++ 中存储数字,为什么我们需要 int?

C++:在最后优化时计算零

C++11 局部命名引用返回值(xvalue)?

c++ - Boost::log:基于级别的不同格式(HTML 格式)

c++ - 当存在用户定义的移动分配运算符时,模板化的移动分配运算符被删除