模板方法的实例和 std::vector.begin() 作为参数的问题
An issue with template method's instance and std::vector.begin() as argument
我想创建一个重载类operator()
方法,它可以接受任何类型的迭代器(包括指针)作为参数。我尝试使用模板:
class SimpleFunction
{
public:
virtual double operator()(double x) = 0;
template<class Iterator> void operator()(Iterator x, Iterator y, unsigned int n);
void operator()(const vector<double> &x, const vector<double> &y);
};
template<class Iterator> void SimpleFunction::operator()(Iterator x, Iterator y, unsigned int n)
{
while (x != x + n)
*y++ = operator()(*x++);
}
void SimpleFunction::operator()(const vector<double> &x, const vector<double> &y)
{
operator()(x.begin(), y.begin(), x.size());
}
但是当我试图编译我的代码时,我得到一个错误:
D:MyFilesfunctionssimple.cpp:9: error: C3892: 'y' : you cannot assign to a variable that is const
我不明白为什么我得到这个错误,因为std::vector
必须有begin()
方法,返回非常量迭代器。我怎样才能避免这个错误?
std::vector
具有const重载的begin
和end
成员函数。因此,在调用operator()(x.begin(), y.begin(), x.size());
的模板中,Iterator
被推导为vector<double>::const_iterator
。如果你想修改传入的矢量y
,不要让它是const vector<double>&
:
void SimpleFunction::operator()(const vector<double> &x, vector<double> &y)
请注意,如果您坚持要求x
和y
具有不同的类型,则需要使用两个模板类型参数,而不是一个:
template<class Iterator, class IteratorY> void SimpleFunction::operator()(IteratorX x, IteratorY y, unsigned int n)
相关文章:
- C++复杂情况的比较器通过参数问题
- C++17 中的歧义错误(模板模板参数和默认参数问题)
- C 缺少模板参数问题
- C++ pcap_loop() 参数问题
- 带有指针作为参数问题的 C++ 函数
- C++ 奇怪的字符*参数问题(不兼容的类型)
- JNA 参数问题:内存访问无效
- Qt样式表和"一个参数"问题
- 默认参数问题 (c++)
- 具有可变模板的递归继承和继承参数问题
- 命令行参数问题
- OpenCV 决策树参数问题
- winapi GetProcessMemoryInfo 无效参数问题
- 参数问题?至少我认为是这样
- 构造函数参数问题C++
- c++教程参考参数问题
- c++多线程参数问题
- Clang Format多行函数声明参数问题
- 提升Python - 具有默认参数问题的重载函数
- VBA Excel DLL参数问题-第6个参数