By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,918 Members | 2,246 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,918 IT Pros & Developers. It's quick & easy.

Ensure template parameter derived from a particular type?

P: n/a
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
Share this Question
Share on Google+
3 Replies


P: n/a
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

P: n/a
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

P: n/a
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.