C++我有一个模板类,它有一个方法print(),我需要根据类型采取不同的行为

use*_*812 3 c++ templates typechecking

我知道模板的重点是概括你的代码,但我希望该类的一个特定成员函数根据创建的对象类型做出不同的反应.具体来说,我创建了一个类字典,用于创建DictionaryNoun或DictionaryAdjective对象.我有一个Dictionary :: print(),我希望有一个代码结构如下:

Dictionary::print(){
   if(this is a Dictionary<Noun> object){
       // Print my nouns in some special way
   }
   if(this is a Dictionary<Adjective> object){
       // Print my adjectives in some special way
   }
   else{ //Print objects in default way}
}
Run Code Online (Sandbox Code Playgroud)

我的问题是如何对我的对象进行类型检查?

tem*_*def 5

C++允许您专门化特定模板参数的成员函数.例如,如果你有这样的东西:

template <typename T> class Dictionary {
    /* ... */
};
Run Code Online (Sandbox Code Playgroud)

然后你就可以专注什么print的做Dictionary<Noun>的写作

template <>
    void Dictionary<Noun>::print() {
    /* ... special code for printing nouns ... */
}
Run Code Online (Sandbox Code Playgroud)

你可以以Adjective同样的方式专攻.最后,如果两者都不匹配,您可以编写一个默认实现

template <typename T>
    void Dictionary<T>::print() {
    /* ... catch-all code ... */
}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!