Pass pointer as generic type c++ template -
i'm trying pass pointer (char*) generic function wrote. error " overloaded foo ambiguous in context ". why 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 add 2 pointers, result in non-sensical pointer. imagine e.g. first text @ address 0x7fffff00
, , second 1 in 0x80000100
. after addition on 32-bit machine going get… 0
. zero. null pointer!
perhaps wanted 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 one) compiler can infer template type you, no reason write explicitly foo<std::string>(c,d)
.
Comments
Post a Comment