为什么这段代码无法编译?
#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 an previous question似乎表明这应该可行。