Monday, October 3, 2016

template: detect required argument type of a function and adapt the data consequently

Example: classes' operator () can receive either a type G or a I<G>.
We pass either the argument I<G> or its member x of type G to operator () depending on what the operator is able to take

#include <iostream>

template <typename G> class I{
public:
  G x;
};


template<typename G>
class Caller{   
public:
  template<typename C>
  static void pass(C& c,I<G>& i){c(i.x);}

};

template<typename G>
class Caller<I<G> >{   
public:
  template<typename C>
  static void pass(C& c,I<G>& i){c(i);}
};


template<typename C,typename X>
X getArgumentType(void (C::*f)(X));

template<typename C,typename G>
inline void call(C& c,I<G>& i){
  Caller<typeof(getArgumentType(&C::operator()))>::pass(c,i);
}

 

struct A{
  void operator()(int x){
    std::cout<<"This is A "<<x<<std::endl;
  }
};

struct B{
  void operator()(I<int>& y){
    std::cout<<"This is B "<<y.x<<std::endl;
  }
};



int main(){

  A a;
  B b;
  I<int> y;
  y.x=77;
  call(a,y);
  call(b,y);
}

No comments:

Post a Comment