我正在编写 的实现zip
,但遇到了一些问题。这是一个最小的测试用例:
#include <iostream>
#include <deque>
#include <tuple>
#include <string>
#include <limits>
template <template <typename...> class Container, typename... Types>
Container<std::tuple<Types...>> zip(Container<Types> const&... args) {
unsigned len = commonLength(args...);
Container<std::tuple<Types...>> res;
std::tuple<Types...> item;
for (unsigned i=0; i<len; i++) {
item = getTupleFrom(i, args...);
res.push_back(item);
}
return res;
}
template <class ContainerA, class... Containers>
unsigned commonLength(ContainerA first, Containers... rest, unsigned len=std::numeric_limits<unsigned>::max()) {
unsigned firstLen = first.size();
if (len > firstLen) {
len = firstLen;
}
return commonLength(rest..., len);
}
template <class ContainerA>
unsigned commonLength(ContainerA first, unsigned len=std::numeric_limits<unsigned>::max()) {
unsigned firstLen = first.size();
if (len > firstLen) {
len = firstLen;
}
return len;
}
template <template <typename...> class Container, typename TypeA, typename... Types>
std::tuple<TypeA, Types...> getTupleFrom(unsigned index, Container<TypeA> const& first, Container<Types> const&... rest) {
return std::tuple_cat(std::tuple<TypeA>(first[index]), getTupleFrom(index, rest...));
}
template <template <typename...> class Container, typename TypeA>
std::tuple<TypeA> getTupleFrom(unsigned index, Container<TypeA> const& first) {
return std::tuple<TypeA>(first[index]);
}
int main() {
std::deque<int> test1 = {1, 2, 3, 4};
std::deque<std::string> test2 = {"hihi", "jump", "queue"};
std::deque<float> test3 = {0.2, 8.3, 7, 123, 2.3};
for (auto i : zip(test1, test2, test3)) {
std::cout << std::get<0>(i) << std::get<1>(i) << std::get<2>(i) << std::endl;
}
//expected output:
//1hihi0.2
//2jump8.3
//3queue7
return 0;
}
编译时出现以下错误:
error: no matching function for call to ‘commonLength(const Star::List<int>&, const Star::List<std::basic_string<char> >&, const Star::List<float>&)’
note: candidates are:
note: template<class ContainerA, class ... Containers> unsigned int Star::commonLength(ContainerA, Containers ..., unsigned int)
note: template<class ContainerA> unsigned int Star::commonLength(ContainerA, unsigned int)
我假设我指定我的模板参数错误或类似的东西。我还尝试重新构建并完全消除该功能,但随后我遇到了同样的错误getTupleFrom
。
谁能给我解释一下我为什么笨?因为我只是不知道我做错了什么。:(