When to use CRTP ?

M

mathieu

Hi there,

I am reading the following post:

http://groups.google.com/group/comp.lang.c++/browse_thread/thread/2805ab0a765aa0ad

And I do not understand the following:

....
- static polymorphism which allows the inheritance or cooperation of
traits and useful specialization under metaprogramming (factorizing
operations by example).
....

So as in the original post, I do not understand what is the added
value of CRTP. Could someone please provide an example where
inheritance of traits clearly requires CRTP, thanks !

-Mathieu
 
S

SG

mathieu said:
  So as in the original post, I do not understand what is the added
value of CRTP.

See the Wikipedia article. It contains some examples. The Barton-
Nackman-trick is another example for a CRTP application with its own
Wikipedia article. (Boost.Operators use this trick as far as I can
tell)

Boost.uBLAS also uses CRTP, although, I'm not 100% sure about how and
why. Maybe someone knowledgable here can shed some more light on what
Boost.uBLAS actually does w.r.t. CRTP.

Cheers,
SG
 
A

Alf P. Steinbach

* mathieu:
Hi there,

I am reading the following post:

http://groups.google.com/group/comp.lang.c++/browse_thread/thread/2805ab0a765aa0ad

And I do not understand the following:

...
- static polymorphism which allows the inheritance or cooperation of
traits and useful specialization under metaprogramming (factorizing
operations by example).
...

So as in the original post, I do not understand what is the added
value of CRTP. Could someone please provide an example where
inheritance of traits clearly requires CRTP, thanks !

I've got a headache so I'm not going to look up the original thread.

But here's an example of CRTP in action, off the cuff (may have syntax erors):

#include <iostream>

using namespace std;

template< class WorkerKind >
struct Worker
{
void sayHello() const
{
WorkerKind const& self = *static_cast<WorkerKind const*>( this );
cout << "Hello, I'm a " << self.kind() << "!" << endl;
}
};

struct Electrician: Worker<Electrician>
{
char const* kind() const { return "electrician"; }
};

struct Plumber: Worker<Plumber>
{
char const* kind() const { return "plumber"; }
}

int main()
{
Plumber().sayHello();
Electrician().sayHello();
}

Oh well it's not inheritance of "traits", didn't see that.

Cheers & hth.,

- Alf
 

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
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top