【发布时间】:2013-09-05 16:21:03
【问题描述】:
为什么这段代码无法编译?
#include <iostream>
#include <vector>
template<class T>
class vector_ref
{
public:
vector_ref(T *pData, int pN) {Data = pData; N = pN;};
T *Data;
int N;
vector_ref<T>& operator=(const std::vector<T> &v1)
{
for(int ii = 0; ii < N; ii++)
{
Data[ii] = v1[ii];
}
return *this;
};
operator std::vector<T>()
{
std::vector<T> v1(N);
for(int ii = 0; ii < N; ii++)
{
v1[ii] = Data[ii];
}
return v1;
};
};
template<class T>
void printVec(std::vector<T> v1)
{
for(int ii = 0; ii < v1.size(); ii++)
{
std::cout << v1[ii] << std::endl;
}
}
int main()
{
std::vector<double> v;
v.push_back(1.0);
v.push_back(2.0);
v.push_back(3.0);
vector_ref<double> v_ref(&v[0],3);
printVec(v_ref); // Compiler error
return 0;
}
我正在使用g++ 4.7.3 使用以下命令进行编译:g++ test.cpp。错误信息是:
test.cpp: In function ‘int main()’:
test.cpp:56:19: error: no matching function for call to ‘printVec(vector_ref<double>&)’
test.cpp:56:19: note: candidate is:
test.cpp:40:6: note: template<class T> void printVec(std::vector<T>)
test.cpp:40:6: note: template argument deduction/substitution failed:
test.cpp:56:19: note: ‘vector_ref<double>’ is not derived from ‘std::vector<T>’
this answer to a previous question似乎暗示这应该可行。
【问题讨论】:
-
我认为您需要
void printVec(T v)而不是参数列表中的std::vector<T>。但是,该函数内部的操作将失败。 -
这给出了错误:
error: ‘class vector_ref<double>’ has no member named ‘size’在函数printVec()中。我可以将v1分配给函数内部的vector,但我不想这样做。 -
是的。这就是我在上一条评论中间接指出的。您的
vector_ref没有名为size()的成员函数。您可以编写自己的函数并实现您想要的功能。 -
operator std::vector<T>&()不返回对局部变量的引用吗? -
在我正在处理的代码中,我有大量类似于
printVec()的函数。我宁愿让它们保持原样,并在函数调用中将vector_ref转换为std::vector。如果没有办法做到这一点,我可以改变功能......这不是我的第一选择。
标签: c++ implicit-conversion conversion-operator