我想做这样的事
std::vector<int> foobar()
{
// Do some calculations and return a vector
}
std::vector<int> a = foobar();
ASSERT(a == {1, 2, 3});这个是可能的吗?
发布于 2015-11-18 13:34:02
不幸的是,您不能重载operator==以接受std::initializer_list作为第二个参数(这是一种语言规则)。
但是,您可以定义任何其他函数来接受对initializer_list的const引用。
#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;
}预期结果:
same? : 1发布于 2015-11-18 13:17:15
是:
ASSERT(a == std::vector<int>{1,2,3});发布于 2015-11-18 13:26:29
您必须显式指定右手操作数的类型。例如
std::vector<int> v = { 1, 2, 3 };
assert( v == std::vector<int>( { 1, 2, 3 } ) );因为operator ==是一个模板函数,编译器无法将第二个操作数推断为std::vector<int>类型。
https://stackoverflow.com/questions/33781070
复制相似问题