尝试在编译时编写一个简单的验证器来检查给定的数字是否落在定义的范围内,如下所示。
template<unsigned N> struct valid {static const unsigned value = 0; };
template<0U> struct valid {static const unsigned value = 1; };
template<99U> struct valid {static const unsigned value = 1; };
template<unsigned N> struct validate
{
static const unsigned value = valid< std::min<0U,N> >::value *
valid< std::max<N,99U> >::value;
}
然而,以上失败了—— 错误:无法将模板参数“min<0u, 1u>”转换为“unsigned int” 错误:无法将模板参数“max<1u, 99u>”转换为“unsigned int”
有什么想法吗?
最佳答案
首先,上面的代码不是有效的 C++ 代码。您用于显式模板特化的语法不正确(最后缺少分号)。除此之外:std::min<0U,N>
和 std::max<N,99U>
是函数,不是函数调用。你可能打算写:
template<unsigned N> struct valid {static const unsigned value = 0; };
template<> struct valid<0U> {static const unsigned value = 1; };
template<> struct valid<99U> {static const unsigned value = 1; };
template<unsigned N> struct validate
{
static const unsigned value = valid< std::min(0U,N) >::value *
valid< std::max(N,99U) >::value;
};
关于c++ - 模板元程序中的编译时验证错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54256471/