Search code examples
c++variadic-templatespointer-to-member

Compose data member access in C++


I am trying to access data members by iterating object via pointers to data members.

The idea is to have a variadic template function, which call std::invoke on the first obj and pass the result to the next pointer to data member. Something like

compose x fnList = foldl obj (\x f -> f x) fnList

from the functional world.

Something I got along the way is:

// main.hpp
#include <iostream>
#include <functional>
// initial template to stop recursion
template<typename T>
T getMember(T obj) {
  return obj;
}
// variadic template, where recursive application of 
// pointer to data member should happen
// I think return type should be something like "*Ret"
template<typename T, typename K, typename Ret, typename ... Args>
Ret getMember(T obj, K memberPointer, Args ... args) {
    return getMember(std::invoke(memberPointer, obj), args ...);
}

and

//main.cpp
#include <iostream>
#include "main.hpp"

//inner class
class Engine 
{
    public:
    std::string name;
};
// outer class
class Car
{
    public:
    int speed;
    Engine eng;
};

void main()
{
    Car car;
    car.speed = 1;        
    car.eng.name = "Some Engine Name";

    // should be same as call to id function, returning the only argument
    Car id = getMember(c1);
    // should "apply" pointer to data member to the object and
    // return speed of the car
    int speedOfCar = getMember(car, &Car::speed);
    // should "apply" pointer to data member to the car,
    // pass the resulting Engine further to &Engine::name,
    // return "Some Engine Name"
    std::string nameOfEngineOfCar = getMember(car, &Car::eng, &Engine::name);

    std::cout << nameOfEngineOfCar << std::endl;
}

Compilation can't deduce return type Ret (gcc 5+, C++17) Is it even possible? What are the limitation (can it be done in C++14)?


Solution

  • You cannot deduce a template argument which only appears in the function return type position. But template argument deduction is not the only kind of deduction in C++. You can do this:

    template <class Bar, class Baz>
    auto foo(Bar x, Baz y) 
          -> decltype(auto) { 
        return moo(x, y); 
    }
    

    If this fails due to old compiler, a safer fallback is

    template <class Bar, class Baz>
    auto foo(Bar x, Baz y)
         -> decltype(moo(x, y)) { 
        return moo(x, y); 
    }