Compile Time checks using templates.

A

Amit

Greetings.

I am looking through some of the examples in Stroustrup's book and he has
certain examples of doing compile time checks for a variety of things.
One of them being the following...

template<class T, class B> struct Derived_from {
static void constraints(T* p) { B* pb = p; }
Derived_from() { void(*p)(T*) = constraints; }
};

struct B { };
struct D : B { };
struct DD : D { };
struct X { };

int main()
{
Derived_from<D,B>();
Derived_from<DD,B>();
Derived_from<X,B>();
}

Obviously the first, two get complied and the third one doesn't, which is
obvious looking at the code.
However, my question is about the template and how this whole thing works.

Basically in the above template, p is defined to be a function pointer and
is assigned to the function 'constraints'.
Not at any point is the function being called, to actually evaluate if the
assignment is being actually done or not. I know this is related to the way
templates and function templates are instantiated(only when they are
referenced). But, I am just trying to understand how exactly this is done.

So, basically when the compiler sees the reference to the "constraints'
function, it instantiates that template function for the said parameters and
checks whether the code is being compiled ?
A little more explanation would be more helpful.

I know this is also mentioned in the Vandervoode book about Templates and
how the instantiation is done, but I don't have that book with me right now.

Thanks.
 
S

Srini

The third template instantiation fails. This is because, when the
compiler encounters the statement,
Derived_from<X,B>();

It will have to generate an appropriate template instance for
'Derived_from' that takes 'struct X' and 'struct B' as its template
parameters. This would look something like this.

struct Derived_from {
static void constraints(X* p) { B* pb = p; }
Derived_from() { void(*p)(T*) = constraints; }
};

In this piece of code, X is not derived from B. So, the assignment

B* pb = p;

will fail. There's no way to convert from X* to B*. Once the particular
template instance is generated, it'll be compiled to verify
correctness. Since the pointer assignment fails, the compiler will
throw up an error.

Hope this was a clear explanation

Regards,
Srini
 

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,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top