简体   繁体   中英

C++ Variadic Template to Evaluate Pointer to Member

I would like to create a variadic template that evaluates nested pointer to members. I have tried the following:

template<typename T, typename U, typename... V>
auto getField(T &input, U (T::*field), V... args)
    -> decltype(getField(input.*field, &args...))
{
    getField(input.*field, &args...);
}

template<typename T, typename U>
U getField(T &input, U (T::*field))
{
    return input.*field;
}

struct inner {
    int val;
};

struct outer {
    inner in;
};

void main() {
    outer p{{5}};
    cout << getField(p, &outer::in, &inner::val) << endl;
}

When I compile the above in VS, I get the following error messages:

error C2672: 'getField': no matching overloaded function found
error C2893: Failed to specialize function template 'unknown-type getField(T &, UT::* ,V...)'
note: With the following template arguments:
note: 'T=outer'
note: 'U=outer::inner'
note: 'V={int outer::inner::* }'

How can I fix the above variadic template to compile, and return p.in.val ? Note that my compiler doesn't support auto template parameters.

Change order of methods and fix "typos":

template<typename T, typename U>
U getField(T &input, U (T::*field))
{
    return input.*field;
}

template<typename T, typename U, typename... V>
auto getField(T &input, U (T::*field), V... args)
    -> decltype(getField(input.*field, args...))
{
    return getField(input.*field, args...);
}

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM