Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 {
like image 923
Mathieu Van Nevel Avatar asked Dec 15 '25 18:12

Mathieu Van Nevel


1 Answers

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();
};
like image 194
Sam Varshavchik Avatar answered Dec 17 '25 07:12

Sam Varshavchik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!