c++classtemplatesattributesfunction-templates

How to use attribute (not its value) of a struct/class as template/function parameter?


To be short, I want to achieve something like "templatize" the operation of "getting an attribute of a object" as a generalized template function, like the function foo below.

template <
    typename T, 
    // something like
    "attribute" obj // or T::obj
>
"sth refer to type of obj" foo(T t)
{
    return t.obj; 
}

What I hope to achieve is, with any simple struct/class like

struct A
{
    int b; 
    type_of_c c; 
    ...
} a; // for any class/struct A with (non-function) attribute b in any type

foo<A, A::b>(a) may return a.b, and foo<A, A::c>(a) may return a.c.

So my question is, how can I express T::obj to set the information of "specifying attribute obj of class T" as the parameter of template?

Some limitations in my programming:


Solution

  • You can make use of pointer to members. To avoid having three template parameter, you can also make use of template argument deduction as shown below.

    template < typename T, typename U>
    U foo2(U (T::*obj), T t)
    {
        return (t.*obj); 
    }
    int main()
    {
        std::cout << foo2(&A::b, a);
    }
    

    Working demo


    Solution 2

    If you're okay with passing three template argument you can also do:

    template < typename T, typename U, U (T::*obj)>
    U foo(T t)
    {
        return (t.*obj); 
    }
    int main()
    {
        std::cout << foo<A, int, &A::b>(a);
    }