假设我有以下类(class):
struct Color
{
enum {
blue,
red,
unknown
};
};
如果类 Color 具有未知值,我想在编译时进行测试。
我认为以下方法可行,但目前返回的结果不正确。
#include <iostream>
template <typename T, typename U = T>
struct test
{
static constexpr bool value = false;
};
template <typename T>
struct test<T, decltype(T::unknown)>
{
static constexpr bool value = true;
};
int main()
{
std::cout << test<Color>::value << std::endl; //prints 0
}
您能否提供一些有关我如何完成检查的见解? 或者我的示例有什么问题?
谢谢
最佳答案
当你写 test<Color>
, 我们首先实例化 test
的主要特化,其中包括填写默认模板参数。所以我们得到 test<Color, Color>
.
接下来,我们尝试查看是否有任何专业匹配。一个专业是 test<Color, Color::<unnamed>>
.这不匹配,所以我们坚持使用主要的!
这种类型不匹配就是为什么 void_t
存在 - 以便我们在主节点上的默认模板参数可以匹配特化:
template <typename T, typename U = void>
// ~~~~~~~
struct test
{
static constexpr bool value = false;
};
template <typename T>
struct test<T, void_t<decltype(T::unknown)>>
// ~~~~~~~ ~
{
static constexpr bool value = true;
};
此外,更喜欢只继承自 false_type
和 true_type
, 分别。
关于c++ - 使用特化测试类中值的存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47563079/