Link to home
Start Free TrialLog in
Avatar of shuklasunil
shuklasunil

asked on

Passing Template to a Template function.

I have defined a template class in following way,

template <class T>
class Vars
{
public:
static int x;
};

class vars0{};
class vars1{};
class vars1{};

typedef Vars<vars0> temp0;
typedef Vars<vars1> temp1;
typedef Vars<vars2> temp2;

int temp0::x =0;
int temp1::x =1;
int temp2::x =2;

I am trying to write a function that will copy the static member variables from one instance of above template class to another

I have tried this&#8230;

template<Vars<typename> class B, Vars<typename> class C>
void Copy()
{
B::x = C::x;
}

&#8230;but is not working.

How can above functionality be implmented. I would also like to insure that the typename passed to this template function should be of type Vars<class T> (though T can be any type)
Avatar of AlexFM
AlexFM

template <class T>
class Vars
{
public:
static int x;
};

class vars0{};
class vars1{};
class vars2{};

typedef Vars<vars0> temp0;
typedef Vars<vars1> temp1;
typedef Vars<vars2> temp2;


template<class B, class C>
void Copy()
{
    B::x = C::x;
}

int temp0::x = 0;
int temp1::x = 1;
int temp2::x = 2;


int main(int argc, char* argv[])
{
    Copy<temp2, temp0>();
    cout << temp2::x << endl;

    return 0;
}
You don't need here template template parameters since parameters of Copy function are ordinal classes. temp2 and temp0 in this case are ordinal C++ classes which are instantiations of Vars template.
Trying to pass classes without static x member to Copy template will not compiled.
ASKER CERTIFIED SOLUTION
Avatar of AlexFM
AlexFM

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
>>I would also like to insure that the typename passed to this template function should be of type Vars<class T> (though
>>T can be any type)

What you want is technically NOT possible, because the function itself must know about the name(s) in the scope, that is whether it(they) refer(s) to a name (a template) or a type. ...Unless you want to specialize your function template for all possible/desired cases of Vars<T>. Probably not what you're asking for. :)

>>How can above functionality be implmented?

I haven't tried this myself, but I would make class Vars an inheritance of a non-template class, i.e.
template <typename T> class Vars : public VarsBase { ... };
then allow you function to take variables of this type VarsBase.