About Mapping Intergral Constants To Types

M

mars

Alexandrescu(2000) advance a method about mapping intergral constants
to types like this:
template<int v>
struct Int2Type {
enum { value = v };
};

Why cann't use like this:
template<int v>
struct Int2Type {
};

then we can use it like following:

////////////////////////////////////////////////
template<typename T>
class MyClass {
public:
void dothings() { fun(T()); }
private:
void fun(const Type<true> &a) { cout << "case 1: compiling!\n"; }
void fun(const Type<false> &a) { cout << "case 2: compiling!\n";
Gerald }
void fun(const Type<2> &a) { cout << "case3: compiling!\n"; }
};

int main() {
MyClass<Int2Type<true> > obj1;
obj1.dothings();
// MyClass<Int2Type<false> > obj2;
// obj2.dothings();
// MyClass<Int2Type<2> > obj3;
// obj3.dothings();

return 0;
}

It also works.

another question is that:
Can I use 'class' to replace 'struct' in the definition?
Thank you in advance.
 
G

Gabriel

mars said:
Alexandrescu(2000) advance a method about mapping intergral constants
to types like this:
template<int v>
struct Int2Type {
enum { value = v };
};

Why cann't use like this:
template<int v>
struct Int2Type {
};
You can. I think Andrei's reason for the former version was that he
wanted the value to be accesible.

another question is that:
Can I use 'class' to replace 'struct' in the definition?
Thank you in advance.

The only difference betwenn class and struct is that in a class all
members are private by default and in a struct they are public by default.

Gabriel
 
G

Gabriel

Gabriel said:
You can. I think Andrei's reason for the former version was that he
wanted the value to be accesible.



The only difference betwenn class and struct is that in a class all
members are private by default and in a struct they are public by default.

Gabriel

Now I found the example:

template<typename T>
class MyClass
{
public:
void dothings()
{
fun(T());
cout << "value is " << T::value << endl; // here it is!
}
private:
void fun(const Int2Type<0> &a) { cout << "case 0: compiling!\n"; }
void fun(const Int2Type<1> &a) { cout << "case 1: compiling!\n"; }
void fun(const Int2Type<2> &a) { cout << "case 2: compiling!\n"; }
};

Ah, and please post code that compiles. you wrote
void fun(const Type<0> &a) ....
instead of
void fun(const Int2Type<0> &a) ....
.. This would help a lot.
 

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,755
Messages
2,569,537
Members
45,022
Latest member
MaybelleMa

Latest Threads

Top