C++ C++;可变模板迭代向量并比较元素
我有一个可变类模板C++ C++;可变模板迭代向量并比较元素,c++,templates,c++11,variadic-templates,C++,Templates,C++11,Variadic Templates,我有一个可变类模板 template <size_t ...T> struct Foo { std::vector<size_t> t; bool IsEqual() { //?? } }; 模板 结构Foo { std::向量t; 布尔·伊斯夸尔() { //?? } }; 我想用它,比如: Foo<1,2,3,4> foo; foo.data = {1,2,3,4}; foo.IsEqual(); Foo-Fo
template <size_t ...T>
struct Foo
{
std::vector<size_t> t;
bool IsEqual()
{
//??
}
};
模板
结构Foo
{
std::向量t;
布尔·伊斯夸尔()
{
//??
}
};
我想用它,比如:
Foo<1,2,3,4> foo;
foo.data = {1,2,3,4};
foo.IsEqual();
Foo-Foo;
foo.data={1,2,3,4};
foo.IsEqual();
如何实现IsEqual来迭代和比较向量的每个元素,并在元素与模板参数的顺序相同时返回false/true?使用索引序列技巧:
bool IsEqual()
{
return t.size() == sizeof...(T) &&
IsEqual(std::make_index_sequence<sizeof...(T)>{});
}
只需解压缩模板参数
template <size_t ...T>
struct Foo
{
std::vector<size_t> t;
bool IsEqualTemplate(size_t index)
{
return true;
}
template <typename FIRSTARG, typename ...OTHERARGS>
bool IsEqualTemplate(size_t index, FIRSTARG firstArg, OTHERARGS... otherArgs)
{
return t[index] == firstArg && IsEqualTemplate(index + 1, otherArgs...);
}
bool IsEqual()
{
return t.size() == sizeof...(T) ? IsEqualTemplate(0, T...) : false;
}
};
模板
结构Foo
{
std::向量t;
布尔IsEqualTemplate(大小索引)
{
返回true;
}
模板
布尔IsEqualTemplate(大小索引、FIRSTARG FIRSTARG、OTHERARGS…OTHERARGS)
{
返回t[index]==firstArg&&isqualtemplate(index+1,其他args…);
}
布尔·伊斯夸尔()
{
返回t.size()==sizeof…(t)?IsEqualTemplate(0,t…):false;
}
};
现在看起来不错。可以简化一点。您不再需要检查索引
。另外,返回X?Y:false
与返回X&&Y
相同。我喜欢三元运算符。:)
bool IsEqual()
{
if (t.size() == sizeof...(T)) {
auto it = t.begin();
bool valid = true;
using expander = int[];
expander{0,
(valid = valid && *it++ == T,
0)...
};
return valid;
}
else {
return false;
}
}
template <size_t ...T>
struct Foo
{
std::vector<size_t> t;
bool IsEqualTemplate(size_t index)
{
return true;
}
template <typename FIRSTARG, typename ...OTHERARGS>
bool IsEqualTemplate(size_t index, FIRSTARG firstArg, OTHERARGS... otherArgs)
{
return t[index] == firstArg && IsEqualTemplate(index + 1, otherArgs...);
}
bool IsEqual()
{
return t.size() == sizeof...(T) ? IsEqualTemplate(0, T...) : false;
}
};