假设我们有以下代码:
template<class T>
void foo(T& v)
{
std::cout<<v[0]<<std::endl;
}
template<class T>
void foo(T* v)
{
std::cout<<v[0]<<std::endl;
}
void main(void)
{
std::vector<int> vec(5,1);
foo(vec);
int* cvec(new int[5]);
cvec[0]=1;
foo(cvec);
}
有没有一种方法可以避免重写第二个函数的主体,只需调用第一个函数(可能进行某种转换或类似的操作)?
更新 也许我的 main 有点误导,但我也想用 C 风格的数组而不是指向 std::vector 的指针来调用 foo。
最佳答案
"is there a way to avoid rewriting the body of the second function, by simply calling the first function (maybe doing some kind of cast or something like that)?"
你可以写
template<class T>
void foo(T& v) {
foo(&v);
}
也将指针传递给 T&
。
或者反过来
template<class T>
void foo(T* v) {
foo(*v);
}
通过取消引用 T*
。
关于c++ - 引用与指针特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26387775/