【发布时间】:2016-08-19 10:26:57
【问题描述】:
所以我有一个类想要为两个类中的一个实例化。我在标题中声明它:
template <class T>
class MyClass {
public:
bool DoSomethingGeneric();
bool DoSomethingTSpecific();
};
由于我不想将方法定义放在头文件中,而是将它们放在实现文件中,并执行显式特化。虽然DoSomethingGeneric 方法可以使用模板进行一般定义,但DoSomethingTSpecific 需要两个单独的实现,一个用于我要实例化MyClass 的两个可能类中的每一个:
template <class T>
bool MyClass<T>::DoSomethingGeneric() {
// Generic code
}
template <>
bool MyClass<ClassA>::DoSomethingTSpecific() {
// ClassA-specific implementation
}
template <>
bool MyClass<ClassB>::DoSomethingTSpecific() {
// ClassB-specific implementation
}
现在,给我一个谜语:我在哪里放置显式专业化?如果我把它放在我的模板定义之后(就像我通常对纯泛型类的专门化所做的那样),clang 说:
explicit specialization of 'MyClass<ClassA>' after instantiation
此消息附带一个指向定义DoSomethingTSpecific 的行的指针。这是有道理的。我的理解是 DoSomethingTSpecific 方法的显式特化算作隐式特化。
同时,如果我将特化放在所有模板定义之后,我会看到:
no function template matches function template specialization 'DoSomethingTSpecific'
这对我来说有点神秘。
有什么想法吗?我怎样才能有一个明确的类级专业化和明确的方法专业化?
【问题讨论】:
-
复制与问题无关。这个复制了它:godbolt.org/g/kbcRK3 请注意,添加了显式类专业化。移动该专业化会重现这两个错误。
-
这个godbolt.org/g/umiA5o怎么样?
-
哈!而已!我看到你的回答,我会接受的。