2016-04-25 63 views
1

所以我有一个类想要实例化为两个类中的一个。我宣布它在头:混合显式类专业化和类方法专业化?

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 
} 

现在,谜语我:在哪里我把明确的专业化?如果我把它放在我的模板定义之后(像我一般用纯粹的泛型类的特办),铛说:

explicit specialization of 'MyClass<ClassA>' after instantiation 

此消息是伴随着指针到DoSomethingTSpecific定义行。这是有道理的。我的理解是,DoSomethingTSpecific方法的明确专业化被认为是一种隐含的专业化。

同时,如果我把该特所有的模板定义后,我看到:

no function template matches function template specialization 'DoSomethingTSpecific' 

这个人是怎样的一个谜给我的。

有什么想法?我怎样才能有明确的类级专业化和明确的方法专业化?

+1

不能再现https://godbolt.org/g/zAlT8e – sergej

+1

即再现无关的问题。这一个重现它:https://godbolt.org/g/kbcRK3请注意,增加显式类专业化。移动专业化会重现这两个错误。 – Alex

+0

这个https://godbolt.org/g/umiA5o怎么样? – sergej

回答

1

从C++标准§14.7.3(5)显式专业化重点矿山):以相同的方式作为成员定义

一个明确专门类模板的成员是 的正常类,不使用template<>语法

实施例:

template <> // specialization for classA 
class MyClass<ClassA> { 
public: 
    bool DoSomethingTSpecific(); // must be declared here 
}; 

// template<> is not used here 
bool MyClass<ClassA>::DoSomethingTSpecific() { 
    // ClassA-specific implementation 
} 

演示:

http://cpp.sh/3tc2g