mardi 3 janvier 2017

What is the correct way to pass a std::vector to be a parameter?

There is a function with std::vector parameter:

class MyClass
{
public:
    MyClass(int){};
};
void test(const std::vector<MyClass>& v)
{
}
int main() 
{
    MyClass c(2);
    std::vector<MyClass> v;
    v.push_back(2);
    test(v);
    test({2});
    test({c});
    return 0;
}

Since I don't want MyClass to be copied, I change the type to std::reference_wrapper.

class MyClass
{
public:
    MyClass(int){};
};
void test(const std::vector<std::reference_wrapper<MyClass>>& v)
{
}
int main() 
{
    MyClass c(2);
    std::vector<std::reference_wrapper<MyClass>> v;
    test(v);
    //test({2});//wrong
    test({c});
    return 0;
}

It works. However, I can't pass the {2} parameter anymore, which is a convenient grammer for me.

So I implement both reference version and no-reference version test function.

class MyClass
{
public:
    MyClass(int){};
};
void test(const std::vector<std::reference_wrapper<MyClass>>& v)
{
}
void test(const std::vector<MyClass>& v)
{
}
int main() 
{
    MyClass c(2);
    std::vector<std::reference_wrapper<MyClass>> v;
    test(v);
    test({2});
    //test({c});//wrong ambigious
    return 0;
}

It's still not the best way, since the test({c}) will be ambigious. The compiler does not know which one to be chosen.

So I'm confused that what is the correct way to solve this kind of problem. Does anyone know this?

Aucun commentaire:

Enregistrer un commentaire