Partial specialized specialization by class

I am looking for the best way to do this. I have a piece of code that needs to handle several different objects that contain different types. The structure that I have looks like this:

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
}

      

Now I need to add some additional functionality that only applies to one of the derived classes. In particular, the output is std :: string, but the type doesn't really matter. The class is large enough that I would rather not copy the whole thing just to specialize a small part of it. I need to add a few functions (both accessory and modifier) ​​and modify the body of several other functions. Is there a better way to do this?

+2


source to share


2 answers


In the template definition, impose another level of indirection:



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
}

      

+4


source


You don't need to specialize the whole class, just what you want. Works with GCC and 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;
}

      

+4


source







All Articles