我有以下代码,我想为容器大小制作一个模板(例如 vector 、数组、列表等) 主要是我定义了一个 vector ,并从模板中调用了 mysize 函数,但我得到了一个错误:“参见 mysize 的声明”。有人可以帮忙吗??
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
template <typename I, typename Op>
Op mysize(I first, I last)
{
auto it = 0;
while (first != last) {
++first;
it += 1;
}
return it;
}
void main()
{
vector<int> v = {1,2,3,4,5,6,7,8};
auto _begin = v.begin();
auto _end = v.end();
auto result = mysize(_begin, _end);
}
最佳答案
无法推导出Op
类型。
这应该有效:
template <typename I, typename Op = std::size_t>
Op mysize(I first, I last)
{
auto it = 0;
while (first != last) {
++first;
it += 1;
}
return it;
}
或者:
template <typename I>
std::size_t mysize(I first, I last)
{
std::size_t it = 0;
while (first != last) {
++first;
++it;
}
return it;
}
或者:
template <typename I>
std::size_t mysize(I first, I last)
{
return std::distance(first, last);
}
关于c++ - 容器模板,错误在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38859134/