template class question (more elegant soln)

A

Anonymous

I want to be able to restrict the set of classes for which a template
class can be instantiated (i.e enforce that all instantiation MUST be
for classes taht derive from a base type BaseType).

This occured to me immediately, but use of a dummy variable is not
elegant - are there other (more elegant) ways of doing this?


template <class DerivedType>
class MyClass
{
public:
MyClass():m_type(*DerivedType){};
~MyClass(){}

private:
BaseType * m_type ; //dummy variable
};
 
V

Victor Bazarov

Anonymous said:
I want to be able to restrict the set of classes for which a template
class can be instantiated (i.e enforce that all instantiation MUST be
for classes taht derive from a base type BaseType).

This occured to me immediately, but use of a dummy variable is not
elegant - are there other (more elegant) ways of doing this?


template <class DerivedType>
class MyClass
{
public:
MyClass():m_type(*DerivedType){};
~MyClass(){}

private:
BaseType * m_type ; //dummy variable
};

The combination of 'Boost::enable_if' with 'base_or_derived' temlplate
helpers should essentially do what you ask, I think.

V
 
G

Gianni Mariani

Anonymous said:
I want to be able to restrict the set of classes for which a template
class can be instantiated (i.e enforce that all instantiation MUST be
for classes taht derive from a base type BaseType).

This occured to me immediately, but use of a dummy variable is not
elegant - are there other (more elegant) ways of doing this?


template <class DerivedType>
class MyClass
{
public:
MyClass():m_type(*DerivedType){};
~MyClass(){}

private:
BaseType * m_type ; //dummy variable
};


Something like this would be better:
template <class DerivedType>
class MyClass
{
static_assert(is_derived(DerivedType,BaseType));
public:
MyClass()
{}

private:
BaseType * m_type ; //dummy variable
};

I have not used them but I think you'll find static_assert and
is_derived in boost.
 
R

Robi-Wan-Kenobi

I am asking myself why do you want to do that?
I think in that case a template is not needed at all. You can make a
class that's holding a pointer (or more of them) to your BaseType as
an aggregation and you can assign any derivedType to that (these)
pointer(s).
But maybe you can explain why you need a template here.

Greetings
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top