简体   繁体   English

将指针作为通用类型C ++模板传递

[英]Pass pointer as generic type c++ template

I'm trying to pass a pointer (char*) to a generic function i wrote. 我正在尝试将指针(char *)传递给我编写的通用函数。 But i get an error " Overloaded foo ambiguous in this context ". 但是我收到一个错误“在这种情况下,重载foo不明确”。 Why does this happen? 为什么会这样?

template <class T>
T foo(T a, T b)
{
    return a+b;
}
int main()
{
    char *c="Hello",*d="world";
    foo<char*>(c,d);
    return 0;
}

It have no reason to add two pointers, it result in a non-sensical pointer. 它没有理由添加两个指针,这将导致一个无意义的指针。 Imagine eg that the first text is at address 0x7fffff00 , and the second one is in 0x80000100 . 想象一下,例如第一个文本位于地址0x7fffff00 ,第二个文本位于0x80000100 Then after an addition on 32-bit machine you going to get… 0 . 然后,在32位计算机上加法后,您将得到… 0 Zero. 零。 Null pointer! 空指针!

Perhaps you wanted to use string's instead, like: 也许您想使用字符串代替,例如:

#include <string>

template <class T>
T foo(T a, T b)
{
    return a+b;
}

int main()
{
    std::string c="Hello", d="world";
    foo(c,d);
    return 0;
}

Also note: in many cases (like this one) compiler can infer template type for you, so no reason to write it explicitly like foo<std::string>(c,d) . 还要注意:在许多情况下(例如这种情况),编译器可以为您推断模板类型,因此没有理由像foo<std::string>(c,d)那样显式地编写模板类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM