为什么函数不能通过返回类型重载?

发布于 2024-10-05 18:09:11 字数 575 浏览 1 评论 0原文

可能的重复:
按返回类型重载函数?
谜题:根据返回值重载 C++ 函数

因为我有一个库,它以以下形式公开了一堆函数:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

薄情伤 2024-10-12 18:09:11

您不能重载返回类型,因为不强制在函数调用表达式中使用函数的返回值。

例如,我可以直接说

GetVal();

编译器现在做什么?

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?

箹锭⒈辈孓 2024-10-12 18:09:11

函数的返回类型不是由编译器生成的用于唯一标识每个函数的重整名称的一部分。以下各项:

  • 参数数量
  • 参数类型
  • 参数序列

是用于为每个函数生成唯一的损坏名称的参数。正是基于这些独特的损坏名称,即使名称相同(重载),编译器也可以理解要调用哪个函数。

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).

慈悲佛祖 2024-10-12 18:09:11

您可以尝试

  1. templateT GetVal(T) {...} 相反(使用虚拟变量来执行解析)
  2. 使用类型转换

或者仅使用简单的 GetValBool 等。

You can try

  1. template <typename T> T GetVal(T) {...} instead (using a dummy variable to perform resolution)
  2. Use type conversions

Or just use the simplistic GetValBool etc.

╭ゆ眷念 2024-10-12 18:09:11

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() (with T varying).

一绘本一梦想 2024-10-12 18:09:11

不,您不能根据返回类型进行重载。

来自标准文档第 13.1.2 节,

仅返回类型不同的函数声明不能​​被重载。

对于您的库,每个函数可能属于不同的命名空间,否则也不可能重载。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文