views:

250

answers:

2

I was trying to solve a problem, but found a different solution. however out of curiosity like to know if the following is possible:

template< class > struct S;
template< > struct S< Foo > : struct< Foo > {};

I would like to be able to inherit nonspecialized struct from specialized struct.the example above does not work because the inherited struct is the specialized, leading to the infinite recursion.

One possible solution was to add second template parameter, say bool specialized, such that the default is false, and specialized template has that parameter is true.however that makes things a bit messy since instantiation needs to specify additional parameter.

Is there some other way around to implement the above?

the original problem was to implement matrix of matrixes, where matrix itself may have additional operators, depending if the constituent matrixes has those operators.I would hope that makes sense. at the same time different specialized matrix need to be of the same base class at the same time retaining the same name, although with different template parameters. I have thought there might be a way to do it using enable_if and type traits

A: 

One possible solution was to add second template parameter, say bool specialized, such that the default is false, and specialized template has that parameter is true.however that makes things a bit messy since instantiation needs to specify additional parameter.

You can do template<class Foo, bool flag = false>, so the second parameter is optional.

sepp2k
+2  A: 

You could keep all the generic stuff in a separate type, and extend that with your specialisation:

template <typename> struct S_generic { /* generic stuff here */ };

template <typename T> struct S : public S_generic<T> { /* nothing here */ };
template <> struct S<Foo> : public S_generic<Foo> { /* extra stuff here */ };

Edit: Alternatively, if you don't like the extra name, the way to use an extra flag without messiness when instantiating the template is to use a default value:

template <typename T, bool fully_defined=true> struct S;
template <typename T> struct S<T,false> { /* generic stuff here */ };

template <typename T> struct S<T,true> : public S<T,false> {};
template <> struct S<Foo,true> : public S<Foo,false> { /* extra stuff here */ };
Mike Seymour
this is what i ended up doing. what i was trying to avoid is having two different names. i think there might be a way to do it using enable_if and type traits.
aaa
There is no reason to add all the extra complication of enable_if or type traits, just use a common base that non-specialized and specialized can inherit from. `BlahBase` or `blah_base` are common.
Roger Pate
at this point it is not so much practical question, as the matter of curiosity, "i wonder if it can do this?".
aaa