gpt4 book ai didi

c++ - 引用与指针特化

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:20:57 25 4
gpt4 key购买 nike

假设我们有以下代码:

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/

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