我有一个类似的模板:
template <typename T>
class MyThing {
public:
static void Write(T value) { ... }
static void Flush() { ... }
}
对于特定类型,例如bool
,我想专门化Write
方法而不修改其他方法。像这样的事情...
// 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) { ... }
}
如何专门化模板类中的其中一个方法?
最佳答案
解决这个问题很简单......
我需要做的就是在我的 .cc 文件中定义该方法:
template <>
void MyThing<bool>::Write(bool value) { ... }
然后在我的 .h 文件中声明它:
template <>
void MyThing<bool>::Write(bool value);
我花了一段时间才弄清楚这一点,所以我想我应该发布它。
关于C++ 模板特化 - 仅特化某些方法,其余方法使用默认 impl,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26536711/