c++ - 如何使用 BOOST_STATIC_ASSERT

标签 c++ templates boost name-lookup

#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 一起工作?

谢谢

最佳答案

你的 template<typename T> void accepts_values_between_1_and_10_alternative(T i)未编译,因为运行时参数是在模板实例化后计算的。在函数范围内,语句 BOOST_STATIC_ASSERT(i >=1 && i < 10); , 表示 i正在查找为非类型模板参数。但是,在封闭的命名空间范围内,i是一个运行时参数,仅查找其类型 以实例化 int对于 T .但是值 6(即使它是程序中的常量表达式)仅在模板实例化之后计算,并且在模板参数推导期间在函数范围内不可见。

为您的template<int i> void accepts_values_between_1_and_10() , i正在查找以实例化 5对于 i ,并且此值传播回 BOOST_STATIC_ASSERT .

关于c++ - 如何使用 BOOST_STATIC_ASSERT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8631769/

相关文章:

c++ - 为什么语句 “vector<int>(v1);”会失败

c++ - 从 C++ 文件中提取 JSON 数据

C++,模板参数错误

c++ - 捕获子类内部的变量?

c++ - boost::spirit::lex 和空格的问题

c++ - 在 C++ 中创建自己的数据范围

c++ - 使用不同方法的置换函数的运行速度导致意外结果

c++ - 为什么编译会导致 missing template arguments 错误?

boost - 如何将 boost 库 1_65 或 1_64 添加到 Visual Studio 2017 项目?

C++根据运行时值选择要使用的虚拟基类的实现