如何使用BOOST_STATIC_ASSERT

4
#include <iostream>
#include <boost/static_assert.hpp>

using namespace std;

// I understand how the following template function works
// template <class T>
// T GetMax (T a, T b) {
//   T result;
//   result = (a>b)? a : b;
//   return (result);
// }    

// I have difficulties to understand how the following code works
// when we should use this syntax
template<int i> void accepts_values_between_1_and_10() {
  BOOST_STATIC_ASSERT(i >=1 && i < 10);
  cout << "i(between 1 and 10): " << i << endl;
}

// I created the following function to test the understanding of BOOST_STATIC_ASSERT
template<typename T> void accepts_values_between_1_and_10_alternative(T i) {
  BOOST_STATIC_ASSERT(i >=1 && i < 10);
  cout << "i(between 1 and 10): " << i << endl;
}

int main () {

  const int i = 5;
  accepts_values_between_1_and_10<i>();

  const int j = 6;
  accepts_values_between_1_and_10_alternative(j);

  return 0;
}

// $> g++ -o template_function -Wall -g template_function.cpp 
// template_function.cpp: In function ‘void accepts_values_between_1_and_10_alternative(T) [with T = int]’:
// template_function.cpp:33:48:   instantiated from here
// template_function.cpp:23:1: error: ‘((i > 0) && (i <= 9))’ is not a valid template argument for type ‘bool’ because it is a non-constant expression

问题1>以下语句的语法是什么?我们应该在何时使用它?如果这是一个模板特化,为什么我们需要提供一个参数而不只是

template<int> void accepts_values_between_1_and_10()
instead of
template<int i> void accepts_values_between_1_and_10()

template<int> void accepts_values_between_1_and_10(int i)
instead of
template<int i> void accepts_values_between_1_and_10()

问题2> 如果我们必须使用这种形式,那么在函数作用域内采用这种语法是真实的吗?

问题3> 如何纠正accepts_values_between_1_and_10_alternative的定义,以使其与BOOST_STATIC_ASSERT一起工作?

谢谢


2
Static-assert 只适用于编译时常量表达式,例如模板参数。它不适用于普通函数参数。C++11 和 C11 添加了 static_assert 语言结构,因此您将不再需要 Boost。 - Kerrek SB
1个回答

5
你的 template<typename T> void accepts_values_between_1_and_10_alternative(T i) 无法编译,因为运行时参数在模板实例化后才被评估。在函数作用域中,语句 BOOST_STATIC_ASSERT(i >=1 && i < 10); 意味着 i 被视为非类型模板参数。但是,在封装的命名空间作用域中,i 是一种运行时参数,仅查找其类型以实例化 Tint。然而,即使在你的程序中它是常量表达式,值 6 也要在模板实例化后才进行评估,在函数作用域中模板参数推导期间不可见。
对于你的 template<int i> void accepts_values_between_1_and_10()i 被查找以实例化 i 的值为 5,并将该值传递回 BOOST_STATIC_ASSERT

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接