tags:

views:

181

answers:

2

I'm looking for a better way to this. I have a chunk 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 derivative classes. Specifically the std::string derivation, but the type doesn't actually matter. The class is big enough that I would prefer not copy the whole thing simply to specialize a small part of it. I need to add a couple of functions (and accessor and modifier) and modify the body of several of the other functions. Is there a better way to accomplish this?

+4  A: 

Impose another level of indirection in the template definitions:

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
}
Novelocrat
+3  A: 

You don't have to specialize the whole class, only what you want. Works with 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;
}
Matt Fichman
Yes... but I also need to add additional methods to the class.
Jonathan Swinney