代码之家  ›  专栏  ›  技术社区  ›  Jonathan Swinney

类上的部分模板专用化

  •  2
  • Jonathan Swinney  · 技术社区  · 17 年前

    我正在寻找更好的方法。我有一段代码需要处理几个包含不同类型的不同对象。我的结构如下:

    class Base
    {
        // some generic methods
    }
    
    template <typename T> class TypedBase : public Base
    {
        // common code with template specialization
        private:
            std::map<int,T> mapContainingSomeDataOfTypeT;
    }
    template <> class TypedBase<std::string> : public Base
    {
        // common code with template specialization
        public:
            void set( std::string ); // functions not needed for other types
            std::string get();
        private:
            std::map<int,std::string> mapContainingSomeDataOfTypeT;
            // some data not needed for other types
    }
    

    现在,我需要添加一些只适用于其中一个派生类的附加功能。特别是std::string派生,但类型实际上并不重要。这门课足够大,我不想简单地复制整个课程来专门化其中的一小部分。我需要添加一些函数(以及访问器和修饰符),并修改其他几个函数的主体。有更好的方法来完成这一点吗?

    2 回复  |  直到 16 年前
        1
  •  4
  •   Phil Miller    17 年前

    在模板定义中施加另一个间接级别:

    class Base
    {
        // Generic, non-type-specific code
    };
    
    template <typename T> class TypedRealBase : public Base
    {
         // common code for template
    };
    
    template <typename T> class TypedBase : public TypedRealBase<T>
    {
        // Inherit all the template functionality from TypedRealBase
        // nothing more needed here
    };
    
    template <> class TypedBase<std::string> : public TypedRealBase<T>
    {
        // Inherit all the template functionality from TypedRealBase
        // string-specific stuff here
    }
    
        2
  •  4
  •   Matt Fichman    17 年前

    你不必专攻整个班级,只需要你想要的。与GCC和MSVC合作:

    #include <string>
    #include <iostream>
    
    class Base {};
    
    template <typename T>
    class TypedBase : public Base
    {
    public:
        T get();
        void set(T t);
    };
    
    // Non-specialized member function #1
    template <typename T>
    T TypedBase<T>::get() 
    {
       return T();
    }
    
    // Non-specialized member function #2
    template <typename T>
    void TypedBase<T>::set(T t) 
    {
        // Do whatever here
    }
    
    // Specialized member function
    template <>
    std::string TypedBase<std::string>::get() 
    {
        return "Hello, world!";
    }
    
    int main(int argc, char** argv) 
    {
        TypedBase<std::string> obj1;
        TypedBase<double> obj2;
        std::cout << obj1.get() << std::endl;
        std::cout << obj2.get() << std::endl;
    }