简体   繁体   English

C ++模板专业化-仅专门化某些方法,其余使用默认的impl

[英]C++ template specialization - specialize only some methods, using default impl for the rest

I have a template like: 我有一个类似的模板:

template <typename T>
class MyThing {
 public:
  static void Write(T value) { ... }
  static void Flush() { ... }
}

For a specific type, eg bool , I want to specialize the Write method without modifying the other methods. 对于特定类型,例如bool ,我想专门研究Write方法而不修改其他方法。 Something like this... 像这样

// Specialize Write() behavior for <bool> ...
// This won't work. Mything<bool> no longer has a Flush() method!
template <>
class MyThing<bool> {
 public:
  static void Write(bool value) { ... }
}

How do I specialize just one of the methods in a template class? 如何仅对模板类中的一种方法进行专门化处理?

The fix for this turns out to be simple ... 解决这个问题很简单...

All I need to do is to define the method in my .cc file: 我需要做的就是在.cc文件中定义方法:

template <>
void MyThing<bool>::Write(bool value) { ... }

And then declare it in my .h file: 然后在我的.h文件中声明它:

template <>
void MyThing<bool>::Write(bool value);

It took me a while to figure this out, so I thought I'd post it. 我花了一些时间才弄清楚这个问题,所以我认为应该将其发布。

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

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