Reputation: 2965
I have a templated class
template< std::size_t Size >
class Buffer
{
....
};
I'd like to prevent instantiation of this template when the Size argument is zero. i.e. generate a compiler warning for the following.
Buffer< 0 > buf;
but all other variants would work.
Buffer< 10 > buf;
I'm looking at using boost::enable_if_c but I don't understand how to get it working.
--Update-- I can't use any c++11 features, unfortunately
Upvotes: 4
Views: 282
Reputation: 96835
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");
};
Upvotes: 0
Reputation: 9547
Simply specialize the template to a state that cannot be instatiated:
template <>
class Buffer<0>;
That way the class cannot be constructed. Usage will result in:
error: aggregate ‘Buffer<0> buf’ has incomplete type and cannot be defined
Upvotes: 10
Reputation: 409356
If your compiler support it, try static_assert
:
template< std::size_t Size >
class Buffer
{
static_assert(Size != 0, "Size must be non-zero");
// ...
};
Upvotes: 6
Reputation: 26060
Utilizing BOOST_STATIC_ASSERT
might be even easier:
#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;
}
Upvotes: 9
Reputation: 145359
#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
}
Upvotes: 1