问题
Possible Duplicates:
Function overloading by return type?
Puzzle: Overload a C++ function according to the return value
Because I have a library which exposes a bunch of functions in the form of:
bool GetVal();
double GetVal();
int GetVal();
long GetVal();
//So on.
And now I have to wrap these. I'd rather not rewrite the same set of functions again. I'd like to do something like
template<class T>
T GetVal(){}
But I can't seem to get this working. Any ideas?
回答1:
You can't overload on return types as it is not mandatory to use the return value of the functions in a function call expression.
For example, I can just say
GetVal();
What does the compiler do now?
回答2:
The return type of functions is not a part of the mangled name which is generated by the compiler for uniquely identifying each function. Each of the following:
- Number of arguments
- Type of arguments
- Sequence of arguments
are the parameters which are used to generate the unique mangled name for each function. It is on the basis of these unique mangled names that compiler can understand which function to call even if the names are same(overloading).
回答3:
You can try
template <typename T> T GetVal(T) {...}
instead (using a dummy variable to perform resolution)- Use type conversions
Or just use the simplistic GetValBool
etc.
回答4:
There's only one function in C++ that can be overloaded by return type, the implicit conversion operator special function, named operator T()
(with T
varying).
回答5:
No, you can't overload based on the return type.
From standard docs., Sec 13.1.2,
— Function declarations that differ only in the return type cannot be overloaded.
And regarding your library, each function might belong to a different namespace or else it ain't possible either.
来源:https://stackoverflow.com/questions/4331837/why-cant-functions-be-overloaded-by-return-type