I'm not sure if this is an error with my C++ syntax, or if this is something that cannot be accomplished at all.
I want to define a class that takes a std::map as a constructor argument. I then want to create an instance of that class by passing a "temporary" (appropriate to call this "rvalue"?) std::map. I.e. I do not want to create an lvalue std::map and then pass that to the constructor.
Can this be accomplished? I have tried the following (commented lines show failed attempts)
#include <map>
#include <string>
#include <iostream>
class Test
{
public:
Test(std::map<int,char>& rMap)
{
std::map<int,char>::iterator iter;
for (iter = rMap.begin(); iter != rMap.end(); ++iter)
{
mMap[iter->first] = mMap[iter->second];
}
}
virtual ~Test(){}
protected:
std::map<int, char> mMap;
};
int main()
{
std::cout << "Hello world!" << std::endl;
//Test test({1,'a'}); // Compile error.
//Test test(std::map<int,char>(1,'a')); // Also compile error.
//Test test(std::map<int,char>{1,'a'}); // Yet again compile error.
return 0;
}
This is my compiler:
g++ (GCC) 4.4.7 20120313 (Red Hat 4.4.7-11)
Compile errors can be posted upon request, but I'm not sure if they would be useful if my problem is syntactic.
Thank you.
Do
Test(std::map<int, char> rMap) : mMap(std::move(rMap)) {}
or
Test(std::map<int, char>&& rMap) : mMap(std::move(rMap)) {}
or
Test(const std::map<int, char>& rMap) : mMap(rMap) {}
Temporary cannot bind to non const l-value reference.
And use it as
Test test({{1,'a'}});
Test test2({{1,'a'}, {2, 'b'}});
Yes but your constructor takes an lvalue reference. It must instead be a reference-to-const, or an rvalue reference.
Just like with any other type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With