简体   繁体   中英

'Creating pointer to member of non-class type 'T*'' compiler error

In the code below, I am trying to specialize FieldCompare template

struct A
{
    size_t key;
};

    template <class T, class Field, Field T::*field_ptr>
    class FieldCompare
    {
    };


    template <class T, class Field, Field T::*field_ptr>
    class FieldCompare<T *, Field, field_ptr>
    {
    };

int main()
{
    FieldCompare<A *, size_t, &A::key> comp;

    return 0;
}

but getting 'creating pointer to member of non-class type 'T*'' compiler error.

what is wrong in this code?

EDIT1:

See the life example of what I am trying to do. It is a specialization of a comparer for using with std::set and std::set, for example

The issue here is that you cannot identify a member of T through T::*ptr when T is a pointer. With the <type_traits> header, however, you can get around this by having the base template this way:

#include <type_traits>

template <class T, class Field, Field std::remove_pointer_t<T>::*field_ptr>
class FieldCompare
{ /* ... */ };

and the specialized version

template <class T, class Field, Field std::remove_pointer_t<T>::*field_ptr>
class FieldCompare<T*, Field, field_ptr>
{ /* ... */ };

Only having the std::remove_pointer_t in the partial specialization doesn't work, as this wouldn't be a specialization.

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