How to accept mixin template as argument?

Given the mixin structure of a C ++ template, how can I write a function that accepts mixin with a specific component? In this example, how can I pass withAandBin worksWithA()?

struct Base {};

template <class T>
struct HasA : T
{
    int A;
};

template <class T>
struct HasB : T
{
    int B;
};

void WorksWithA(HasA<Base> &p)
{
    p.A++;
}

void WorksWithAandB(HasA<HasB<Base> > &p)
{
    p.A++;
    p.B++;
}

int _tmain(int argc, _TCHAR *argv[])
{
    HasA<Base> withA;
    HasA<HasB<Base> > withAandB;

    WorksWithA(withA); // OK
    WorksWithAandB(withAandB); // OK
    WorksWithA(withAandB); // KO, no conversion available

    return 0;
}

Even putting aside the problem of constructing or streamlining the mixing ( HasA<HasB<Base>>vs HasB<HasA<Base>>), I do not see a good way to write this function, in addition to making it also a template.

I am currently working in an environment without C ++ 11, but I would be interested if modern C ++ provided this solution.

Thank you so much!

+4
source share
5 answers

WorksWithA , , HasA:

template<typename T>
void WorksWithA(HasA<T> &p)
{
  p.A++;
}

.

+2

, ?

template <class T>
void WorksWithA(HasA<T> &p)
{
    p.A++;
}

template <class T>
void WorksWithAandB(HasA<HasB<T> > &p)
{
    p.A++;
    p.B++;
}

HasA<HasB<Base>> HasA<Base>.

+2

, , , , . , , :

template<class B> 
void WorksWithA(HasA<B> &p) 
{ 
    p.A++; 
} 

template<class B> 
void WorksWithB(HasA<B> &p) 
{ 
    p.B++;
}

template<class Has>
void WorksWithAandB(Has &p)
{
    WorksWithA(p);
    WorksWithB(p);
}

WorksWithAAndB . :

  • .
  • , WorksWithA WorksWithB , WorksWithAAndB.
+2

WorksWithA ; . : WorksWithA , HasA. .

+1

, , HasA HasB , :

struct HasA
{
  int A;
  virtual ~HasA() = default;
};

struct HasB
{
  int B;
  virtual ~HasB() = default;
};

struct HasAB : HasA, HasB
{
};

struct Base : HasAB
{};

void WorksWithA(HasA &p)
{
  p.A++;
}

void WorksWithAandB(HasAB &p)
{
  p.A++;
  p.B++;
}

WorkWithA , WithA, WorksWithAandB , HasAB.

PS: , WorksWithAandB , HasA, HasB HasAB, SFINAE.

+1

Source: https://habr.com/ru/post/1651041/


All Articles