Mathieu Van Nevel Mathieu Van Nevel - 6 days ago 7
C++ Question

Template partial specialization on bool

That's a really basic question I think, but I was'nt able to find an answer, even on StackOverflow. So sorry if you want to hit me when you'll read this.

I just want to do a partial specialization on bool value :

template < typename Object, bool Shared = false >
class Foo {

void bar();
};

template < typename Object >
void Foo<Object, true>::bar() {}

template < typename Object >
void Foo<Object, false>::bar() {}

int main() {

Foo<int> test;
return 0;
}


I think the idea is correct, but I'm missing something with this code (probably really stupid) :

Test3.cpp:8:30: error: invalid use of incomplete type ‘class Foo<Object, true>’
void Foo<Object, true>::bar() {
^
Test3.cpp:2:7: note: declaration of ‘class Foo<Object, true>’
class Foo {
^~~
Test3.cpp:13:31: error: invalid use of incomplete type ‘class Foo<Object, false>’
void Foo<Object, false>::bar() {
^
Test3.cpp:2:7: note: declaration of ‘class Foo<Object, false>’
class Foo {

Answer

Your template defines a class, not a function. That means that you have to specialize that class, not the class method:

template < typename Object >
class Foo<Object, false> {
  void bar();
};

template < typename Object >
class Foo<Object, true> {
  void bar();
};