开发者

Convert vector to map with pointers to members?

I'm having trouble understanding why the code below

#include <string>
#include <vector>
#include <map>

using namespace std;

struct Student { int id; string name; };

template<typename T, typename U, U T::* Member>
map<U, T> group_by(const vector<T> &items)
{
    map<U, T> result;
    for (vector<T>::const_iterator it = items.begin(); it != items.end(); 开发者_开发百科++it)
        result[it->*Member] = *it;
    return result;
}

int main()
{
    vector<Student> items;
    group_by<Student, int, Student::id>(items); //Error
    return 0;
}

gives this error:

*error C2440*: 'specialization' : cannot convert from `''` to `'int Student::* const '`  

Context does not allow for disambiguation of overloaded function

How do I fix this?


it is not a pointer to a Student so you can't use it with the ->* member access operator`. I think you meant:

result[(*it).*Member] = *it;

To form a pointer to member, you need to use &, it is not optional. You also need to introduce dependent type names (such as vector<T>::const_iterator with typename).

This version compiles for me:

#include <string>
#include <vector>
#include <map>

using namespace std;

struct Student { int id; string name; };

template<typename T, typename U, U T::* Member>
map<U, T> group_by(const vector<T> &items)
{
    map<U, T> result;
    for (typename vector<T>::const_iterator it = items.begin(); it != items.end(); ++it)
        result[(*it).*Member] = *it;
    return result;
}

int main()
{
    vector<Student> items;
    group_by<Student, int, &Student::id>(items);
    return 0;
}


I think the error should be different.

Student::id cannot appear in a constant expression as a template parameter.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜