Reputation: 996
so I have a piece of code that I am attempting to test. The code is checking that a few vectors (these are elements of structs) are equivalent to known vectors at certain points, however I am running into an issue. When I attempt to compare the vector to the known vector as follows,
assert((class1.getattr().getattr().getVec(key) == {4,3,2,2}))
I get the following error:
assertAll.cpp:105:82: error: could not convert ‘{4,3,2,2}’ from ‘<brace-enclosed initializer list>’ to ‘std::vector<int>’
the rest of the code is all correct, and the lval of the assert is definitely a vector as it should be. I am compiling with the flags, -std=c++11 -Wall -Wextra -pedantic -O in g++. Does anybody know how to fix this? Is there a way to typecast the bracket enclosed initializer list to a vector, or is there a better way to do this?
Upvotes: 0
Views: 3451
Reputation: 505
Does anybody know how to fix this? Is there a way to typecast the bracket enclosed initializer list to a vector
Interestingly, I get a completely different error on Clang 3.5 and GCC 4.9.2 when I try something similar, but you can just use the initializer list syntax to construct a vector in place (not quite typecasting, I guess):
assert((class1.getattr().getattr().getVec(key) == std::vector<int>{4,3,2,2}))
I'm not sure how to do that thing where you can run code on Coliru and such, but the following code works for me on GCC 4.9.2 using g++ -std=c++11 -Wall -pedantic
#include <cassert>
#include <vector>
std::vector<int> foo() {
return {1,2,3,4};
}
template<class T>
bool is_equal(const T& a, const T& b) {
return a == b;
}
int main()
{
assert((foo() == std::vector<int>{1,2,3,4}));
assert(is_equal(foo(), {1,2,3,4}));
assert([&](std::vector<int> v) -> bool {
return foo() == v;
}({1,2,3,4}));
}
Granted, nobody in their right mind would use a lambda like that, but as you might be able to tell from the examples, you basically just need to tell the compiler that the two sides are the same type in order to get it to convert the initializer list to a vector.
Upvotes: 1