I want to do something like
std::vector<int> foobar()
{
// Do some calculations and return a vector
}
std::vector<int> a = foobar();
ASSERT(a == {1, 2, 3});
is this possible?
I want to do something like
std::vector<int> foobar()
{
// Do some calculations and return a vector
}
std::vector<int> a = foobar();
ASSERT(a == {1, 2, 3});
is this possible?
Unfortunately you cannot overload operator==
to accept a std::initializer_list
as the second argument (this is a language rule).
But you can define any other function to take a const reference to an initializer_list
:
#include <iostream>
#include <algorithm>
#include <vector>
template<class Container1, typename Element = typename Container1::value_type>
bool equivalent(const Container1& c1, const std::initializer_list<Element>& c2)
{
auto ipair = std::mismatch(begin(c1),
end(c1),
begin(c2),
end(c2));
return ipair.first == end(c1);
}
int main() {
std::vector<int> x { 0, 1, 2 };
std::cout << "same? : " << equivalent(x, { 0 , 1 , 2 }) << std::endl;
}
expected result:
same? : 1
Yes:
ASSERT(a == std::vector<int>{1,2,3});
You have explicitly to specify the type of the right hand operand. For example
std::vector<int> v = { 1, 2, 3 };
assert( v == std::vector<int>( { 1, 2, 3 } ) );
because the operator ==
is a template function and the compiler is unable to deduce the second operand to the type std::vector<int>
The most natural and/or 'prettiest' working implementation that I am aware of, assuming that what you want to do is impossible (as people on this site have said multiple times), is to typedef
your vector
type as follows:
typedef std::vector<int> vec;
ASSERT(a == vec({1, 2, 3}));
... where vec
is named whatever you want.
If someone knows of something even more natural, please let us know.