通过我实现了Python的连锁功能的C++相当于前一段时间由于可变参数模板。该函数用于连续遍历许多容器。下面是使用一个名为ChainedObject
发电机的功能,不管它是旧的工作版本:类型推演和论证与可变参数模板模板
template<typename... Iterables>
auto chain(Iterables&&... iters)
-> ChainObject<Iterables...>
{
return /* ... */;
}
和相应的主:
int main()
{
std::vector<int> vec = { 1, 2, 3, 4, 5 };
std::list<int> li = { 6, 7, 8, 9, 10, 11, 12, 13 };
for (auto& i: chain(vec, li))
{
// You can edit a range of iterables
// as if there was only one of them.
i *= 5;
std::cout << i << std::endl;
}
return 0;
}
这主要工作得很好。我们不在乎ChainObject中存在什么问题,所以让我们来看看它。我试图用模板模板,以确保所使用的不同集合有同样的value_type
和修改功能chain
方式如下:
template<typename T, template<typename...> class... Iterables>
auto chain(Iterables<T>&&... iters)
-> ChainObject<T, Iterables...>
{
return /* ... */;
}
我认为这会做的伎俩,以确保我以前主要的list
和vector
共享相同的类型,而是,我从GCC 4.7.1以下错误:
In function 'int main()':
error: no matching function for call to 'chain(std::vector&, std::list&)'
note: candidates are:
note:
ChainObject<T, Iterables ...> chain(Iterables<T>&& ...) [with T = int; Iterables = {std::vector, std::list}
]note: no known conversion for argument 2 from '
std::list<int>
' to 'std::list<int>&&
'note:
ChainObject<T, Iterables ...> chain(Iterables<T>&& ...) [with T = int; Iterables = {std::vector, std::list}]
note: no known conversion for argument 2 from '
std::list<int>
' to 'std::list<int>&&
'error: unable to deduce 'auto&' from ''
看来,问题来自于通过采取右值引用的函数的参数。但是,我真的不明白为什么我的第一个版本运行良好,并注意使用模板模板。
您是否尝试过通过左值引用,而不是右值吗? –
请勿将模板模板与容器组合使用。一旦使用分配器就会失败。只需检查嵌套的'value_type'是否相等。 – pmr