开发者

Partial template specialization question

开发者 https://www.devze.com 2023-02-17 13:44 出处:网络
class FooInterface { virtual void toggle() = 0; }; template <class TYPE, class CONFIG> class Foo : public FooInterface {
class FooInterface {
  virtual void toggle() = 0;
};

template <class TYPE, class CONFIG>
class Foo : public FooInterface {
  virtual void toggle();

  TYPE value_;
};

template <>开发者_运维技巧
void Foo<bool, class CONFIG>::toggle() {
  if (CONFIG::canToggle())
    value_ = !value_;
}

struct MyConfig {
  static bool canToggle() {
    return false;
  }
};

int main() {
  Foo<bool, MyConfig> foo;
}

That's an accurate approximation of what I'm dealing with. I basically want to have a specialized method for dealing with a TYPE, while keeping the CONFIG generic. So, for example, I might have a dozen different Foo::toggle() methods with specialized code handling specific TYPEs, but what's used from CONFIG will be consistent across all of those methods.

The problem is the previous code doesn't compile, along with several different combinations, and I'd appreciate some help finding a different solution or some workaround to make the current one work.

Edit: I should note that the previous code works without the CONFIG template parameter.


You need to partially specialise the whole class. You can't specialise individual member functions.

template <class CONFIG>
class Foo<bool, CONFIG> : public FooInterface
{
   virtual void toggle();
   bool value_;
};  

template <class CONFIG>
inline void Foo<bool, CONFIG>::toggle()
{
   if (CONFIG::canToggle())
     value_ = !value_;
} 


dispatch

template<class CONFIG, class C>
void toggle_impl(type<bool>, C &c) {
  if (CONFIG::canToggle())
    c.value_ = !c.value_;
}

template <class TYPE, class CONFIG>
class Foo : public FooInterface {
  virtual void toggle() {
      toggle_impl<CONFIG>(type<TYPE>(), *this);
  }
  TYPE value_;
};
0

精彩评论

暂无评论...
验证码 换一张
取 消