Ensure template parameter derived from a particular type?

K

kk_oop

Hi. I have a template class Base_t<typename T1, typename T2>. I
intend to instantiate it like this:

class Derived : public Base_t<SomeClass1, SomeClass2>
{
....
};

I'd like to have the compiler ensure that any actual parameter used for
T1 is derived from Class A. So in the example above, I'd like a
compiler error to be generated if SomeClass1 is not derived from Class
A.

Is there a way to do this?

Thanks!

Ken
 
A

Alan Johnson

Hi. I have a template class Base_t<typename T1, typename T2>. I
intend to instantiate it like this:

class Derived : public Base_t<SomeClass1, SomeClass2>
{
...
};

I'd like to have the compiler ensure that any actual parameter used for
T1 is derived from Class A. So in the example above, I'd like a
compiler error to be generated if SomeClass1 is not derived from Class
A.

Is there a way to do this?

Thanks!

Ken

You could use Loki's SuperSubclassStrict template metafunction.
 
F

Frederick Gotham

posted:

I'd like to have the compiler ensure that any actual parameter used for
T1 is derived from Class A. So in the example above, I'd like a
compiler error to be generated if SomeClass1 is not derived from Class
A.

Is there a way to do this?


Here's something that just came to mind, but I haven't sat down and
pondered over the posibilities. It isn't perfect, but it's a step in the
right direction:

#include <cstddef>

class Base {};

class Derived : public Base {};

class NotDerived {};

template<class T>
class TemplateClass {
private:

std::size_t const static assert_base =
sizeof static_cast<const Base&>( T() );

};

int main()
{
TemplateClass<Derived> obj1;

TemplateClass<NotDerived> obj2; /* Compile ERROR */
}
 

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

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top