我需要在编译时对变体类型是否可以容纳一个类型进行类型检查。
我正在将枚举和字符串转换为变体,但我希望库与用户提供的变体(对于它们支持的类型)兼容。所以我有一个模板参数 CustomVariant
来表示受支持类型子集的变体,AlphaBeta
、Gamma
、Delta
和 Epsilon
。如果无法创建有效变体,我想返回 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;
}
关于c++ - 在编译时从变量中获取类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55348169/