尝试在编译时编写一个简单的验证器,以检查给定的数量是否在定义的范围内,如下所示。

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 '转换为'unsigned int'
错误:无法将模板参数'max '转换为'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;
};

try it out here

关于c++ - 模板元程序中的编译时验证错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54256471/

10-15 00:26
查看更多