简体   繁体   English

在编译时/模板检查变量的值

[英]Check the value of a variable at compile time / templates

So, we have this: 因此,我们有:

template<typename T, typename = std::enable_if_t<std::is_integral<T>::value>>
void fun(const T& val)
{
    std::cout << "val >= 0";
}

int main()
{
    fun(34);
}

Imagine we have other overloads of the function. 假设我们还有其他函数重载。 How would I get the above function overload to only compile when the value of val is larger than 0 ? 我如何使上面的函数重载仅在val的值大于0时进行编译?

On http://en.cppreference.com/w/cpp/types/is_integral I see that operator() is overloaded for std::is_integral and it returns the value so I tried this: http://en.cppreference.com/w/cpp/types/is_integral上,我看到std::is_integral operator()重载,并且它返回value所以我尝试了以下操作:

template<typename T, typename = std::enable_if_t<std::is_integral<T>::value() > 0>>

Of course, it looks wrong, and it is wrong as the compiler graciously lets me know. 当然,它看起来是错误的,而且是错误的,因为编译器会很高兴地告诉我。

How do I check the value of the variable at compile time? 如何在编译时检查变量的值?

Short answer: You can't. 简短的回答:不能。

Functions input parameters value is determined at run-time. 函数输入参数值在运行时确定。 Thus, SFINAE won't help at this neither will any else compile time trickery. 因此,SFINAE不会对此有所帮助,其他任何编译时间的技巧也不会。

What you can do is attack the problem at runtime and define two independent functions that are going to be evoked accordingly: 您可以做的是在运行时解决问题,并定义两个将相应地引起的独立功能:

template<typename T, typename = std::enable_if_t<std::is_integral<T>::value>>
void fun(const T& val)
{
    (val < 0)? lower_than_zero(val) : greater_equal_than_zero(val);
}

But probably you knew that already. 但是可能您已经知道了。 If you're still in for compile time evaluation and you're sure that your variable is a compile time beast. 如果您仍在进行编译时评估,并且确定您的变量是编译时的野兽。 Then you could pass it as a template non-type argument: 然后,您可以将其作为模板非类型参数传递:

template<int N>
std::enable_if_t<N >= 0> fun() {
  std::cout << "N >= 0" << std::endl;
}

template<int N>
std::enable_if_t<N < 0> fun() {
  std::cout << "N < 0" << std::endl;
}

int main() {
  fun<42>();
  fun<-42>();
}

As @101010 answered there is no way to do this in general way. 正如@ 101010回答的那样,无法以一般方式执行此操作。 But if you need to check only one condition >= 0 , then you can do this: 但是,如果您只需要检查>= 0一个条件,则可以执行以下操作:

void ff(unsigned int val) {
    val = 42;
}

int main()
{
    ff(34);
    ff(-34);
}

and compile like this: 并像这样编译:

g++ 1.cpp -Werror -Wsign-conversion

But it's just a hack for one special case. 但这只是一个特殊情况的骇客。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM