Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restricting the size of an array when passed to a function

Tags:

c++

arrays

Is there anyway to restrict the size of an array when passed as an argument to a function?

I mean is something like this possible?

/*following will lead to compile time error */

template<typename T, size_t n>=20> // or template<typename T,size_t n<=20>
void func(T (&a)[n])
{
   // do something with a

}

I want the size of my array to be at least(or at most) n(n can have any value).

For example:

When n=20 I must pass an array with at least(or at most) 20 elements. Is there any way in C++ for this?

like image 298
Prasoon Saurav Avatar asked Jan 29 '10 09:01

Prasoon Saurav


2 Answers

You can simply make the requirement a static assertion - e.g. with Boosts static assert:

template<typename T, size_t n> 
void func(T (&a)[n]) {
    BOOST_STATIC_ASSERT(n >= 20);
    // ...
}

A basic custom implementation (not solving the problem of using it more then once per scope) might look like the following:

template<bool b> struct StaticAssert;
template<> struct StaticAssert<true> {};
#define STATIC_ASSERT(x) StaticAssert<(x)> static_asserter 

If you want different behaviour if the requirement is met, use something like enable_if or tag-based specialization. Example using enable_if:

template<class T, size_t n>
typename boost::enable_if<(n >= 20), void>::type
func(T (&a)[n]) { /* ... */ }

template<class T, size_t n>
typename boost::disable_if<(n >= 20), void>::type
func(T (&a)[n]) { /* ... */ }
like image 116
Georg Fritzsche Avatar answered Nov 16 '22 02:11

Georg Fritzsche


GF's answer is correct, if you want more features or decisions points at compile time, you might want to look at boost::mpl. C++ Template Metaprogramming outlines what is possible with boost::MPL and how it was designed. Modern C++ design, which is not related to MPL, goes into design techniques which leverage compile time polymorphism

like image 30
Hassan Syed Avatar answered Nov 16 '22 02:11

Hassan Syed