c++ - 引用与指针特化

标签 c++ templates pointers reference

假设我们有以下代码:

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/

相关文章:

c++ - 模板特化/初始化和命名空间?

email - 如何使用 Grails 外部化 GSP 邮件模板?

c++ - BST 不添加元素

c++ - C++中的模板类

c - Swift:将未初始化的 C 结构传递给导入的 C 函数

c++ - 当列表中有两个以上的项目时,链表的函数添加会崩溃?

c++ - 当退出 new/malloc 函数时,如何将 new/malloc 返回的指针保留在范围内?

C++ 异常返回类型为什么是 char*

c++ - boost::numeric_cast 功能无一异常(exception)

c++ - 这个数组大小模板是如何工作的?