3

following from this question, I have been trying to create a template function that calls all same-named methods of its mixins. This has been done and verified in the previous question.

Now I am attempting to get the return value of SensorType::

Analytically:

#include<iostream>
#include <string>

struct EdgeSensor
{
    void update(int i) { std::cout << "EdgeSensor::update " << i <<  std::endl; }
    void updat2(const int i ) { std::cout << "EdgeSensor::updat2" << i << std::endl; }
    std::string printStats() { std::cout << "EdgeSensor::printStats" << std::endl; 
                               return std::string("EdgeSensor::printStats"); }
};

struct TrendSensor
{
    void update(int i ) { std::cout << "TrendSensor::update" << i << std::endl; }
    void updat2(const int i ) { std::cout << "TrendSensor::updat2" << i << std::endl; }
    std::string printStats() { std::cout << "TrendSensor::printStats" << std::endl; 
                               return std::string("TrendSensor::printStats"); }
};

template <class T, void (T::*)(const int)>
struct Method { };

template<typename ... SensorType>
class BaseSensor : public SensorType ... //to my BaseSensor class
{
   template <class T, void(T::*M)(const int)>
   int runSingle(Method<T, M> , const int i) {
      (this->*M)(i);
      return 0;
   }

   template <class... Ts>
   void runAll(const int i) {
      int run[sizeof...(Ts)] = { runSingle(Ts{},i)... };
      (void)run;
   }

public:
    void update() {
       runAll<Method<SensorType, &SensorType::update>...>(2);
    }
    void updat2() {
       const int k = 3;
       runAll<Method<SensorType, &SensorType::updat2>...>(k);
    }
    void printStats() {
    //   runAll<Method<SensorType, &SensorType::printStats>...>();
    }
};

int main() {
  {
    BaseSensor<EdgeSensor,TrendSensor> ets;
    ets.update();
    ets.updat2();
    ets.printStats();
  }

  {
    BaseSensor<EdgeSensor> ets;
    ets.update();
    ets.updat2();
    ets.printStats();
  }
}

The above compiles and runs fine. The problem is: how can I gather the return values (std::strings) from running the mixin SensorType::printStats() methods in BaseSensor::printStats() ?

If I try to create a 2ndary version of the run* functions and the Method template, I fail to make it compile. Say I did:

template <class T, void (T::*)()>
struct Method2 { };

template <class T, void(T::*M)()>
int runSingle2(Method2<T, M>) {
    (this->*M)();
    return 0;
}

template <class... Ts>
void runAll2() {
    std::string s;
    int run[sizeof...(Ts)] = { s = runSingle2(Ts{})... };
    (void)run;
    std::cout << "s=" << s << std::endl;
}

public:
    void update() {
        int k = 4;
        runAll<Method<SensorType, &SensorType::update>...>(k);
    }
    void printStats() {
        runAll2<Method2<SensorType, &SensorType::printStats>...>();
    }
};

This does not compile saying

g++ -Wall -Wextra -g -std=c++11   -c -o "obj_dbg/main.opp" "main.cpp"
main.cpp: In instantiation of ‘void BaseSensor<SensorType>::printStats() [with SensorType = EdgeSensor, TrendSensor]’:
main.cpp:65:20:   required from here
main.cpp:58:8: error: could not convert template argument ‘&EdgeSensor::printStats’ to ‘void (EdgeSensor::*)()’
make: *** [obj_dbg/main.opp] Error 1

So HOW can I grab the return values from SensorType::printStats()?

Community
  • 1
  • 1
nass
  • 1,453
  • 1
  • 23
  • 38

3 Answers3

2

Here is you code reviewed so as it works as requested:

#include<iostream>
#include <string>
#include <vector>

struct EdgeSensor
{
    void update(int i) { std::cout << "EdgeSensor::update " << i <<  std::endl; }
    void updat2(const int i ) { std::cout << "EdgeSensor::updat2" << i << std::endl; }
    std::string printStats() { std::cout << "EdgeSensor::printStats" << std::endl; 
    return std::string("EdgeSensor::printStats"); }
};

struct TrendSensor
{
    void update(int i ) { std::cout << "TrendSensor::update" << i << std::endl; }
    void updat2(const int i ) { std::cout << "TrendSensor::updat2" << i << std::endl; }
    std::string printStats() { std::cout << "TrendSensor::printStats" << std::endl; 
    return std::string("TrendSensor::printStats"); }
};

template<typename ... SensorType>
class BaseSensor : public SensorType ... {
    template<typename F>
    struct Invoke;

    template<typename R, typename... A>
    struct Invoke<R(A...)> {
        template <R(SensorType::* ...M)(A...), typename T>
        static std::vector<R> run(T *t, A... args) {
            std::vector<R> vec;
            int arr[] = { (vec.push_back((t->*M)(args...)), 0)... };
            (void)arr;  
            return vec;
        }
    };

    template<typename... A>
    struct Invoke<void(A...)> {
        template <void(SensorType::* ...M)(A...), typename T>
        static void run(T *t, A... args) {
            int arr[] = { ((t->*M)(args...), 0)... };
            (void)arr;  
        }
    };

public:
    void update() {
       Invoke<void(int)>::template run<&SensorType::update...>(this, 2);
    }
    void updat2() {
       const int k = 3;
       Invoke<void(int)>::template run<&SensorType::updat2...>(this, k);
    }
    void printStats() {
         auto vec = Invoke<std::string(void)>::template run<&SensorType::printStats...>(this);
         for(auto &&v: vec) {
             std::cout << "--->" << v << std::endl;
        }
    }
};

int main() {
  {
    BaseSensor<EdgeSensor,TrendSensor> ets;
    ets.update();
    ets.updat2();
    ets.printStats();
  }

  {
    BaseSensor<EdgeSensor> ets;
    ets.update();
    ets.updat2();
    ets.printStats();
  }
}

I refactored a bit the code, for there was no need for the Method class. This works as intended and the strings returned by the printStats methods are now collected in a std::vector and returned to the caller.

skypjack
  • 49,335
  • 19
  • 95
  • 187
  • Hi there, unfortunately the above does not compile https://godbolt.org/g/tJMtiZ . I have been trying to figure out why, but perhaps you can identify it more easily – nass Sep 24 '16 at 08:15
  • @nass It compiles with [clang](https://godbolt.org/g/Nm8maE), but it doesn't with GCC. I created a [question](http://stackoverflow.com/questions/39665300/gcc-vs-clang-variadic-template-and-pointers-to-member-methods) to explore if it's a problem of GCC or of the code, but no answers yet unfortunately. I'll be back as far as I have some news for you. – skypjack Sep 24 '16 at 08:29
  • ah yes indeed I saw that and been following it :) Perhaps it would be useful to add this info as part of the answer (at least until a solution is provided) – nass Sep 24 '16 at 08:30
  • @nass Quite interesting an error, I would be tempted to say that the code is correct, but I'm not sure 100% that the expansion is valid. ;-) – skypjack Sep 24 '16 at 08:32
2

To extend the solution to any type of member function you could do (and actually a bit simplify it still having in mind c++11 restriction). The approach resolves type of member function to be able to infer its result type. It also uses InferOwnerType to infer mixin type and avoid direct passing of statically casted this pointer. Depending on the result of the member function now we can store it into an array or use the trick with int array just to be sure each member function is invoked.

#include <iostream> // std::cout std::endl
#include <string>   // std::string
#include <utility>  // std::declval

struct EdgeSensor //a mixin
{
    void update(int a){ std::cout << "EdgeSensor::update" << a << std::endl; }
    std::string updat2(int const v) { return "EdgeSensor::printStats"; }
};

struct TrendSensor //another mixin
{
    void update(int a){ std::cout << "TrendSensor::update" << std::endl; }
    std::string updat2(int const v) { return "TrendSensor::printStats"; }
};

template <class Res, class This, class... Args>
This InferOwnerType(Res (This::*foo)(Args...)) { }

template<typename ... SensorType>
class BaseSensor : public SensorType ... //to my BaseSensor class
{
    template <class M, class... Args>
    auto run(M m, Args... args)
       -> decltype((std::declval<decltype(InferOwnerType(m))*>()->*m)(args...)) {
       return (static_cast<decltype(InferOwnerType(m))*>(this)->*m)(args...);
    }

public:
    template <class... Args>
    void update(Args... args) {
       int arr[] = {(run(&SensorType::update, args...), 0)...};
       (void)arr;
    }
    template <class... Args>
    void updat2(Args... args) {
       std::string s[] = {run(&SensorType::updat2, args...)...};
       for (int i = 0; i < sizeof...(SensorType); i++)
          std::cout << s[i] << std::endl;
    }
};

int main() {
   BaseSensor<EdgeSensor, TrendSensor> bs;
   bs.update(4);
   bs.updat2(0);
   BaseSensor<EdgeSensor> bs2;
   bs2.update(1);
   bs2.updat2(0);
}
W.F.
  • 13,888
  • 2
  • 34
  • 81
  • Hi there, once again , in trying to understand what is going on, I have a few questions :) can we talk about them in a chat window? – nass Sep 24 '16 at 09:01
  • http://chat.stackoverflow.com/rooms/123992/discussion-between-nass-and-w-f – W.F. Sep 24 '16 at 11:03
  • 1
    The `InferThisType` is somehow crazy, but intriguing too. :-D – skypjack Sep 24 '16 at 16:24
  • @skypjack Right wording isnt very good maybe `InferOwnerClass` was a better choice... – W.F. Sep 24 '16 at 16:31
  • @skypjack I read your comment in a way and I believe I reinterpret it a bit... you meant treating the member pointer as a say tag to be dispatched is somewhat crazy :) well I admit I'm a bit crazy guy (~o~) – W.F. Sep 24 '16 at 18:28
2

Not sure if you can use c++11, if so, then I think this is the easiest?

#include <iostream>
#include <string>

struct EdgeSensor
{
    void update(int i) { std::cout << "EdgeSensor::update " << i <<  std::endl; }
    void updat2(const int i ) { std::cout << "EdgeSensor::updat2" << i << std::endl; }
    std::string printStats() { std::cout << "EdgeSensor::printStats" << std::endl; 
                               return std::string("EdgeSensor::printStats"); }
};

struct TrendSensor
{
    void update(int i ) { std::cout << "TrendSensor::update" << i << std::endl; }
    void updat2(const int i ) { std::cout << "TrendSensor::updat2" << i << std::endl; }
    std::string printStats() { std::cout << "TrendSensor::printStats" << std::endl; 
                               return std::string("TrendSensor::printStats"); }
};

template<typename ... SensorType>
class BaseSensor : public SensorType ... //to my BaseSensor class
{
public:
    void update() {
       auto v = { (static_cast<SensorType*>(this)->update(1), 0)... }; // *
       (void) v;
    }
    void updat2() {
       const int k = 3;
       auto v = { (static_cast<SensorType*>(this)->updat2(k), 0)... }; // *
       (void) v;
    }
    void printStats() {
       auto v = { static_cast<SensorType*>(this)->printStats()... };
       for (auto s : v) {
           std::cout << s << std::endl;
       }
    }
};

int main() {
  {
    BaseSensor<EdgeSensor,TrendSensor> ets;
    ets.update();
    ets.updat2();
    ets.printStats();
  }

  {
    BaseSensor<EdgeSensor> ets;
    ets.update();
    ets.updat2();
    ets.printStats();
  }
}
  • NOTE: I am using a gcc extension here, but I think you are using gcc, so it should be okay
Nim
  • 33,299
  • 2
  • 62
  • 101
  • Nice!! gcc extension is inferring array type right? – W.F. Sep 23 '16 at 17:23
  • 1
    `auto v = { (this->SensorType::update(1), 0)... };` could be even nicer (allows to avoid possible virtual dispatch error, which can't be done in the member pointer approach) – W.F. Sep 23 '16 at 17:30
  • 1
    @W.F. no, that's part of the standard, however what is not is the usage of the `,` operator here, it's a GCC extension to mean apply expression before the `,`, discard the result, and then apply the expression after the `,` and use it's value. Hence, you have an initializer list with N 0s, – Nim Sep 23 '16 at 17:36