468,456 Members | 1,648 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,456 developers. It's quick & easy.

Ensure template parameter derived from a particular type?

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

Jul 6 '06 #1
3 2006
kk****@yahoo.com wrote:
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.

--
Alan Johnson
Jul 6 '06 #2
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<Derivedobj1;

TemplateClass<NotDerivedobj2; /* Compile ERROR */
}

--

Frederick Gotham
Jul 6 '06 #3
kk****@yahoo.com wrote:
Hi. I have a template class Base_t<typename T1, typename T2>. I
intend to instantiate it like this:
...
I'd like to have the compiler ensure that any actual parameter used for
T1 is derived from Class A.
Look at the discussion of constraints in Stroustrup's C++ FAQ
(http://www.research.att.com/~bs/bs_f...l#constraints),
particularly the Derived_from template.

Jul 6 '06 #4

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

7 posts views Thread by Tony Johansson | last post: by
2 posts views Thread by Siegfried Weiss | last post: by
11 posts views Thread by Niels Dekker - no reply address | last post: by
19 posts views Thread by n.torrey.pines | last post: by
5 posts views Thread by Wayne Shu | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.