tags:

views:

517

answers:

5

Suppose I have code like this:

template<class T, T initial_t> class Bar {
  // something
}

And then try to use it like this:

Bar<Foo*, NULL> foo_and_bar_whatever_it_means_;

GCC bails out with error (on the above line):

could not convert template argument '0' to 'Foo*'

I found this thread: http://gcc.gnu.org/ml/gcc-help/2007-11/msg00066.html, but I have to use NULL in this case (ok, I could probably refactor - but it would not be trivial; any suggestions?). I tried to overcome the problem by creating a variable with value of NULL, but GCC still complains that I pass variable and not address of variable as a template argument. And reference to a variable initialized with default ctor would not be the same as NULL.

A: 

Have you tried:

Bar<Foo*, (Foo*)NULL> foo_and_bar_whatever_it_means_;

?

or reinterpret_cast(0)?

Assaf Lavie
both do not work...
Nicola Bonelli
+3  A: 

Rethinking your code is probably the best way to get around it. The thread you linked to includes a clear quote from the standard indicating that this isn't allowed.

Dan Olson
+2  A: 

It seems to be the same problem as passing a string literal as non-type template parameter: it's not allowed. A pointer to an object is allowed as template parameter if the object has external linkage: this to guarantee the uniqueness of the type.

Nicola Bonelli
A: 

@Dan Olson: there seems to be quite easy workaround.

Create a parent class with only one template parameter. Add a virtual function returning T. For base class it should be hardcoded to be NULL. For deriving class it would return the second template parameter.

phjr
+1  A: 

To accept Bar<Foo, NULL>, you need

template <typename T, int dummy> class Bar; /* Declared but not defined */
template <typename T> class Bar <T,NULL> { /* Specialization */ };

since typeof(NULL)==int.

MSalters