简体   繁体   English

布尔的模板部分专业化

[英]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. 我认为这是一个非常基本的问题,但是即使在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 : 我只想对bool值进行部分专业化处理:

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 {

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();
};

Another way is to decompose foo and treat the implementation of bar in a separate helper class. 另一种方法是分解foo并在单独的帮助器类中处理bar的实现。 This reduces the amount of repetition required to implement Foo. 这减少了实现Foo所需的重复次数。

For example: 例如:

template<class Object, bool Shared>
struct implement_bar;

template<class Object>
struct implement_bar<Object, true>
{
  void operator()(Object& o) const 
  {
    // do true thing with o
  }
};

template<class Object>
struct implement_bar<Object, false>
{
  void operator()(Object& o) const 
  {
    // do false thing with o
  }
};

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

  void bar()
  {
    return implement_bar<Object, Shared>()(*this);
  }
};

int main() {

  Foo<int> test;
  return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM