使用C ++编写数据成员访问权限

时间:2018-11-20 17:14:25

标签: c++ variadic-templates pointer-to-member

我正在尝试通过指向数据成员的指针迭代对象来访问数据成员。

这个想法是要有一个可变参数模板函数,该函数在第一个obj上调用std :: invoke并将结果传递给下一个指向数据成员的指针。 就像是

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

来自功能世界。

我遇到的事情是:

// 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 ...);
}

//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;
}

编译无法推断出返回类型Ret(gcc 5 +,C ++ 17) 可能吗有什么限制(可以在C ++ 14中完成)吗?

1 个答案:

答案 0 :(得分:3)

您不能推导仅出现在函数返回类型位置的模板参数。但是,模板参数推论并不是C ++中唯一的推论。您可以这样做:

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

如果由于旧的编译器而导致失败,则是更安全的后备方式

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