为什么函数不能通过返回类型重载?
因为我有一个库,它以以下形式公开了一堆函数:
bool GetVal();
double GetVal();
int GetVal();
long GetVal();
//So on.
现在我必须包装这些函数。我不想再次重写同一组函数。我想做一些类似的事情
template<class T>
T GetVal(){}
,但我似乎无法让它发挥作用。有什么想法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您不能重载返回类型,因为不强制在函数调用表达式中使用函数的返回值。
例如,我可以直接说
编译器现在做什么?
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
What does the compiler do now?
函数的返回类型不是由编译器生成的用于唯一标识每个函数的重整名称的一部分。以下各项:
是用于为每个函数生成唯一的损坏名称的参数。正是基于这些独特的损坏名称,即使名称相同(重载),编译器也可以理解要调用哪个函数。
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:
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).
您可以尝试
templateT GetVal(T) {...}
相反(使用虚拟变量来执行解析)或者仅使用简单的
GetValBool
等。You can try
template <typename T> T GetVal(T) {...}
instead (using a dummy variable to perform resolution)Or just use the simplistic
GetValBool
etc.C++ 中只有一个函数可以通过返回类型重载,即隐式转换运算符特殊函数,名为
operator T()
(T
可变)。There's only one function in C++ that can be overloaded by return type, the implicit conversion operator special function, named
operator T()
(withT
varying).不,您不能根据返回类型进行重载。
来自标准文档第 13.1.2 节,
对于您的库,每个函数可能属于不同的命名空间,否则也不可能重载。
No, you can't overload based on the return type.
From standard docs., Sec 13.1.2,
And regarding your library, each function might belong to a different namespace or else it ain't possible either.