Prevent template creation with template argument 0

I have a template class

template< std::size_t Size > class Buffer { .... }; 

I want to prevent the creation of an instance of this template when the Size argument is zero. those. create a compiler warning for the following.

 Buffer< 0 > buf; 

but all other options will work.

 Buffer< 10 > buf; 

I am looking at using boost :: enable_if_c, but I don't understand how to make it work.

- Update-- I cannot use any C ++ 11 features, unfortunately

+4
source share
5 answers

Using BOOST_STATIC_ASSERT could be even simpler:

 #include <boost/static_assert.hpp> template< std::size_t Size > class Buffer { BOOST_STATIC_ASSERT(Size != 0); }; int main() { Buffer<0> b; //Won't compile return 0; } 
+9
source

Just specify the template in a state that cannot be set:

 template <> class Buffer<0>; 

Therefore, a class cannot be built. Using will result in: error: aggregate 'Buffer<0> buf' has incomplete type and cannot be defined

+10
source

If your compiler supports it, try static_assert :

 template< std::size_t Size > class Buffer { static_assert(Size != 0, "Size must be non-zero"); // ... }; 
+6
source
 #include <stddef.h> typedef ptrdiff_t Size; template< Size size > class Buffer { static_assert( size > 0, "" ); }; int main() { #ifdef ZERO Buffer<0> buf; #else Buffer<1> buf; #endif } 
+1
source

std::enable_if

 template <std::size_t N, typename = typename std::enable_if<!!N>::type> class Matrix {}; 

static_assert :

 template <std::size_t N> class Matrix { static_assert(N, "Error: N is 0"); }; 
0
source

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


All Articles