samedi 27 décembre 2014

Possible to write the code once for a specific set of different types?

I have a template class TC who's constructor takes parameters who's values are dependent on as well as being of type Tn.


So, I want to create a helper template function htf that will call the same functions of a Tn object to generate a TC for a set of types X0 to Xn. The helper function takes only one parameter from that set. Is it possible, perhaps with variadic templates, to write the function once for the set of types, instead of having to write the same function over and over again for each type?


Now, I could just use a template to allow all types, but I don't want that as there may be another function with the same name written for a specific type later that's not based on this TC. And, IIRC I think SFINAE works with member functions, not pure functions.


This is just an idea in my head at the moment, that's why the question is very general. However, here is roughly the code I'm thinking of, simplified, in an more concrete or an over generalized fashion:



template<typename T1, typename Tn>
class TC
{
T1* m_pT1;
Tn* m_pTn;
TC(T1* pT1, Tn* pTn) : m_pT1(pT1), m_pTn(pTn) {}
friend TC htf(Tn& tn);
public:
~TC() {}
};

// concrete functions:
TC<Y0, X0> htf(X0& x) { return TC<Y0, X0>(&x.fn(), &x); }
TC<Y1, X1> htf(X0& x) { return TC<Y1, X1>(&x.fn(), &x); }
//...
TC<Yn, Xn> htf(X0& x) { return TC<Yn, Xn>(&x.fn(), &x); }

// or in an over generalized template function:
template<typename X>
auto htf(X& x) -> TC<decltype(x.fn()), X>
{
return TC<decltype(x.fn()), X>(&x.fn(), &x);
}

Aucun commentaire:

Enregistrer un commentaire