gpt4 book ai didi

c++ - 模板类中函数的模板参数

转载 作者:行者123 更新时间:2023-11-30 02:55:53 25 4
gpt4 key购买 nike

我有这样的情况

template<class T> class Vector {
T *data;
uint _size, _counter;
public:
class Iterator;
template<template<class> class C> Vector(typename C<T>::Iterator it1,
typename C<T>::Iterator it2) {
data = NULL;
_size = _counter = 0;
for(typename C<T>::Iterator it = it1; it != it2 && it != end(); it++)
push(*it);
}
};

那是我自己的 Vector 类,构造函数模仿 vector 的行为(您可以使用 interators 提供的数据范围来构造它),但增加了容器必须是与正在构建的容器类型相同的模板的要求。我收到错误

5.cpp:16:36: error: no matching function for call to ‘Vector::Vector(Vector::Iterator, Vector::Iterator)’ 5.cpp:16:36: note: candidates are: In file included from 5.cpp:2:0:

5.hpp:17:37: note: template class typedef C C> Vector::Vector(typename C::Iterator, typename C::Iterator)

5.hpp:17:37: note: template argument deduction/substitution failed:

5.cpp:16:36: note: couldn't deduce template parameter ‘template class typedef C C’ In file included from 5.cpp:2:0:

5.hpp:11:3: note: Vector::Vector() [with T = int]

5.hpp:11:3: note: candidate expects 0 arguments, 2 provided

5.hpp:7:25: note: Vector::Vector(const Vector&)

5.hpp:7:25: note: candidate expects 1 argument, 2 provided

这里需要一些帮助。

最佳答案

在:

 template<template<class> class C> Vector(typename C<T>::Iterator it1,
typename C<T>::Iterator it2)

编译器不推导类型C来自 typename C<T>::Iterator因为它就是所谓的非演绎上下文

请参阅第 14.8.2.4 节从类型 [temp.deduct.type] 推导模板参数:

4 The nondeduced contexts are:

— The nested-name-specifier of a type that was specified using a qualified-id.

— A type that is a template-id in which one or more of the template-arguments is an expression that references a template-parameter.

关于c++ - 模板类中函数的模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16093073/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com