Question

If i have this code:

template<int SIZE = 0>
class A {
public:

    union {
        int buf[MagicThing];
        /* ... */
    };
};

Is possible in C++ to make some (macro?) called MagicThing which works this way:

  • if SIZE > 0 then MagicThing == SIZE
  • if SIZE == 0 then MagicThing == 1

At compile time? (Idealy some short trick without needs of using boost library etc.)

Was it helpful?

Solution

You may use:

int buf[SIZE > 0 ? SIZE : 1];

OTHER TIPS

You could try this

int buf[SIZE == 0 ? 1 : SIZE]

and make SIZE unsigned, or add a static_assert to check that the size is non-negative. You didn't specify what behaviour you want when SIZE is less than 0. Presumably that shouldn't happen.

(If SIZE will be always 0 or more, change its type to unsigned.)

A crazy sample solution, which perhaps can be used as idea for other situations (using resources of C++11):

#include <iostream>

/* General case */
template<unsigned SIZE>
constexpr unsigned MagicThing()
{
   return SIZE;
}

/* Partial specialization when SIZE == 0 */
template<>
constexpr unsigned MagicThing<0>()
{
    return 1;
}

template<unsigned SIZE = 0>
class A {
public:
   int buf[MagicThing<SIZE>()];

   size_t size() const
   {
       return sizeof(buf) / sizeof(int);
   }
};

int main()
{
   A<0> a0;
   A<1> a1;
   A<5> a5;

   std::cout << a0.size() << " " << a1.size() << " " << a5.size() << std::endl;
}

/* Compilation and execution */
$ gcc -std=c++11 sample.cpp
$ ./a.out
1 1 5

Other (not the simplest one) possibility would be, using the new static_if directive, proposed for the following standard C++14, the next one (I'm not sure if my syntax is correct):

template<unsigned SIZE = 0>
class A {
public:
   static_if (SIZE > 0)
     int buf[SIZE];
   else
     int buf[1];

   size_t size() const
   {
       return sizeof(buf) / sizeof(int);
   }
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top