How to use BOOST_STATIC_ASSERT

#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 

Question1 What is the syntax of the following statement? And when should we use it? If this is a template specification, why should we provide a parameter, not just

 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() 

Question2 Is it true that we should adopt this syntax in the area of ​​functions if we should use this form?

Question3 How do I fix the definition of accepts_values_between_1_and_10_alternative so that it works with BOOST_STATIC_ASSERT ?

thanks

+4
source share
1 answer

Your template<typename T> void accepts_values_between_1_and_10_alternative(T i) does not compile because the execution parameters are evaluated after the templates are created. In the function area, the operator BOOST_STATIC_ASSERT(i >=1 && i < 10); means that i considered as a parameter of the non-pig type template. However, with the encompassing namespace region, i is a run-time parameter for which only its type is checked to create an int instance for T But the value 6 (although it is a constant expression in your program) is evaluated only after creating the template instance, and it does not appear in the function area while subtracting the template argument.

For << 26> value i checked to create 5 for i , and this value returns to BOOST_STATIC_ASSERT .

+5
source

Source: https://habr.com/ru/post/1387964/


All Articles