Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Could C++ template function overload on return parameter?

With same template declaration, is it possible to differ two functions with same name, same param list, but different return type?

template <class T>
int f()...

template <class T>
short f()...

Or, need some special code to achieve this?

Thanks.

like image 879
Troskyvs Avatar asked May 15 '26 18:05

Troskyvs


1 Answers

You can indeed have function templates with same name, same parameter types, and same return type (but you cannot for regular functions).

template <class T>
int f() {/*..*/}

template <class T>
short f() {/*..*/}

But then their usage is not really easy/fine:

auto i = static_cast<int(*)()>(&f<float>)(); // Call int f<float>
auto s = static_cast<short(*)()>(&f<float>)(); // Call short f<float>
like image 62
Jarod42 Avatar answered May 18 '26 07:05

Jarod42



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!