4

If I want to write a class that has an optional type parameter I can do the following:

template<typename T> struct X { T t; }; template<> struct X<void> { }; int main() { X<int> a; X<void> b; }; 

Is there a way to write it so that the void is unnecessary? ie:

int main() { X<int> a; X b; }; 

I tried this:

template<typename T = void> struct X { T t; }; template<> struct X<void> { }; int main() { X<int> a; X b; }; 

but I get:

test.cpp: In function ‘int main()’: test.cpp:16:4: error: missing template arguments before ‘b’ test.cpp:16:4: error: expected ‘;’ before ‘b’ 
3
  • 1
    The best you can do is X<> b. Commented Dec 24, 2012 at 3:02
  • The only solution I know to not using templates is to make a non-templated sub-class. Commented Dec 24, 2012 at 3:03
  • You did everything correctly in your second attempt, except that you are still required to specify empty <> when instantiating your template with default argument, i.e. it has to be X<> b; Commented Dec 24, 2012 at 3:24

2 Answers 2

4

You technically need to write:

X<> b; 

But you can simply fix that ugliness with a typedef:

typedef X<> Y; 

And then you can do:

Y b; 
Sign up to request clarification or add additional context in comments.

1 Comment

In which case you can just as well do typedef X<void> Y; and avoid the default value.
1

If only this was possible:

template <typename T> using X = std::is_void<T>::value ? _X<> : _X<T> 

But this doesn't compile so unfortunately you are stuck with a typedef like the other answer.

1 Comment

There is typename std::conditional<std::is_void<T>::value, _X<> : _X<T>>::type. I know this is old, but it's worth sharing.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.