Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a std::get like function for my class?

For example, I have a class

struct A {int a; bool b;};

And I want to generate a template function to get its elements (like the std::get to get a tuple element)

template<unsigned i, class T>
auto Get(T& t);

template<>
int& Get<0, A>(A& a)
{
    return a.a;
}

template<>
bool& Get<1, A>(A& a)
{
    return a.b;
}


int main()
{
    A a;
    Get<0>(a) = 10;
    Get<1>(a) = true;
    return 0;
}

The above code doesn't work. The challenge is that I don't know the returned type of Get for arbitrary class. Any way to implement it? Thanks.

like image 464
user1899020 Avatar asked Jul 13 '13 04:07

user1899020


1 Answers

Assuming you wouldn't mind making this in a "manual manner" you can do this really simply.

#include <tuple>

struct A {
    int a; bool b;
};

template<size_t N>
auto get(A& a) -> decltype(std::get<N>(std::tie(a.a, a.b))) {
    return std::get<N>(std::tie(a.a, a.b));
}

#include <iostream>

int main() {
    A a;
    get<0>(a) = 10;
    get<1>(a) = true;
    std::cout << a.a << '\n' << a.b;
}

Output:

10
1
like image 57
Rapptz Avatar answered Sep 24 '22 11:09

Rapptz