thundium thundium - 2 months ago 8
C++ Question

reference used for template parameter

I got following code running

using namespace std;
#include <iostream>

template<typename a> struct function
{
void self1(){ cout << "hello world 1111" << endl; }
};

template<typename a> struct function<a&>
{
void self2() { cout << "hello world 2222" << endl; }
};


int main()
{
function<int> a;
a.self1();
function<int&> b;
b.self2();
return 0;
}


The result is:

hellow world 1111
heloow world 2222


Would like to ask the relation ship between the first "struct function" and the second "struct function"

Is the second one classfied as "template specialization" for the first one? (seems not)

I can see that the 2nd one is based on the 1st one. (By removing the 1st one, it is not compilable). But

b.self1() is not defined.


So somehow the 2nd have redefined the struct to a new one?

Answer

I can see that the 2nd one is based on the 1st one. (By removing the 1st one, it is not compilable). But

b.self1() is not defined. So somehow the 2nd have redefined the struct to a new one?

function is a struct template, it's not a struct by itself. At the moment of instantiating one like you did : function<int> a; the compiler generates a struct function_int that contains int for all T's (or a's in this case).

template<typename a> struct function<a&> 

This is a specialisation of the struct template that's used for when a is a reference type. This specialisation can't use any members/methods of the "original" struct template.

Comments