简体   繁体   中英

c++ overloaded function and templates

I am learning how to use templates in conjunction with function overloading, but I can't seem to grasp it; specifically, I have 2 functions with the same name, one accepts 2 int parameters, the other 3 int parameters. I need them to return, respectively, a double/triple pointer to a type which should be defined by the function caller; in other words:

template <typename T>
T** Foo(int p0, int p1){
    T** ret = nullptr;
    // ... do stuff with ret ...
    return ret;
}

template <typename T>
T*** Foo(int p0, int p1, int p2){
    T*** ret = nullptr;
    // ... do stuff with ret ...
    return ret;
}

int _tmain(int argc, _TCHAR* argv[])
{
    double**  d2 = Foo(1, 2);
    double*** d3 = Foo(1, 2, 3);
    int**     i2 = Foo(1, 2);
    int**     i3 = Foo(1, 2, 3);
}

I was expecting d2 and i2 to be returned by the first Foo(), d3 and i3 by the second; instead I get Errors C2780 and C2783 from each one of the calls in main(). What am I missing?

The compiler cannot automatically deduce the template parameter (because it is only dependant on the return type and not any of the arguments). You should use this code instead:

double**  d2 = Foo<double>(1, 2);
double*** d3 = Foo<double>(1, 2, 3);
int**     i2 = Foo<int>(1, 2);
int***    i3 = Foo<int>(1, 2, 3);

(Note I also made a correction on the final line: you had int** instead of int*** )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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