use of template variables ?

D

digz

#include<cstdio>
template <int role>
struct A
{
void f(){
switch(role) {
case 0:
case 1:
printf("did match\n");
default:
printf("did not match\n");
}
}
};
int main()
{
A<0> a;
A<1> b;
}

This is a simplified representation of a C++ program I came across.
Can someone explain any possible motivation behind this kind of a
construct and what feature of templates has been used while writing
this class. Also is the switch case evaluated at compile time. ? and
as I have said in the subject whats role here , a variable of a
template type or what ?

--Digz
 
V

Victor Bazarov

digz said:
#include<cstdio>
template <int role>
struct A
{
void f(){
switch(role) {
case 0:
case 1:
printf("did match\n");
default:
printf("did not match\n");
}
}
};
int main()
{
A<0> a;
A<1> b;
}

This is a simplified representation of a C++ program I came across.
Can someone explain any possible motivation behind this kind of a
construct

If it's simplified, are you sure you didn't simplify away the actual
motivation? I can't really find anything useful in your template A
at all. What is curious, the 'f' member is not even generated for
any template instantiation in your program since you never acutally
call it.
and what feature of templates has been used while writing
this class. Also is the switch case evaluated at compile time. ?

It can be. The compiler is free to determine that the expression
on which 'switch' branches is constant and not generate code that
is not supposed to be executed, ever (not that it's relevant in
your case here, since there is no 'break' in 'case 1' or 'case 0').
and
as I have said in the subject whats role here , a variable of a
template type or what ?

The term is "non-type template argument". It's not variable since
you cannot assign it any new value.

V
 
D

David Harmon

On Thu, 14 Feb 2008 12:17:56 -0800 (PST) in comp.lang.c++, digz
#include<cstdio>
template <int role>
struct A
{
void f(){
switch(role) {
case 0:
case 1:

When the template function is instantiated, role is a compile time
constant so there is no run-time overhead for the switch.
 

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
474,183
Messages
2,570,965
Members
47,513
Latest member
JeremyLabo

Latest Threads

Top