【问题标题】:std::wstring and LOGFONT overloads conflicting - why?std::wstring 和 LOGFONT 重载冲突 - 为什么?
【发布时间】:2014-02-07 10:54:01
【问题描述】:

我正在开发 GCC 4.8.1 下的 C++ 项目。我有两个 getter/setter 对:

LOGFONT GetTitleBarFont();
void SetTitleBarFont(LOGFONT titleBarFont);

std::wstring GetTitleBarFont();
void SetTitleBarFont(std::wstring titleBarFont);

但出于某种原因,GCC 告诉我这些不是有效的重载。

error: 'std::wstring GetTitleBarFont()' cannot be overloaded
error: with 'LOGFONT GetTitleBarFont()'

我不明白这里的问题是什么。 std::wstring 是一种 STL 类型(准确地说是std::basic_string<wchar_t>),在后台有大量模板工作。 LOGFONT 是一种 Windows 数据类型 (http://msdn.microsoft.com/en-us/library/windows/desktop/dd145037(v=vs.85).aspx),几乎完全由原生 C++ 数据类型(LONGs 和 BYTEs,带有一个奇怪的 TCHAR 数组)组成。这些怎么可能是模棱两可的重载?

【问题讨论】:

  • 你不能重载返回类型。

标签: c++ gcc overloading


【解决方案1】:

您不能根据返回类型重载方法,因为重载决策考虑了函数签名

1.3.11 签名

有关参与重载的函数的信息 分辨率(13.3):它的参数类型列表(8.3.5),如果 函数是类成员,函数上的 cv 限定符(如果有) 本身和声明成员函数的类。 [...]

---编辑---
要详细说明可能的解决方案,您可以

1) 更改 getter 的名称:

std::wstring GetTitleBarFontWString();
LOGFONT GetTitleBarFontLogFont();

2) 输出参数(这个组合不太好,但有时你必须这样做)

void GetTitleBarFont(std::wstring& out);
void GetTitleBarFont(LOGFONT& out);

3) 滥用模板专业化,因此调用者可以指定他想要返回的内容。 (GetTitleBarFont<std::wstring>, GetTitleBarFont<LOGFONT>)

基本上没有很好的解决方案。

3) 全部归功于 chris,2) 部分归功于 chris

【讨论】:

  • 或者,让用户指定类型:GetTitleBarFont<LOGFONT>()GetTitleBarFont<std::wstring>(),或使用参考参数:GetTitleBar(someLOGFONT)GetTitleBar(someWstring)
  • @Xam:基本上没有很好的解决方案 - 是的:正确命名函数。它不返回字体,而是它的name,将其命名为Get/SetTitleBarFontName,没有问题:)
  • @JohannGerell 详细信息... ;-) 假设他出于某种原因想要保持名称相同(即,他想调用 GetTitleBarFront 并获得他想要的返回类型的一些模板魔法)在那里不是,但是是的,重命名 getter 以获取 name 是有意义的。
【解决方案2】:

假设返回字符串的函数没有给出字体,而是一个字体name,显而易见的解决方案是

std::wstring GetTitleBarFontName();
void SetTitleBarFontName(std::wstring titleBarFont);

因为你不能只用返回类型作为鉴别器来重载。

【讨论】:

    【解决方案3】:

    对于遇到此问题并想知道的其他任何人,就像我刚才所做的那样,为什么 C++ 在确定要使用的重载时不考虑返回值:Function overloading by return type? 是一个非常详细的答案,说明为什么这是案例。

    【讨论】:

      猜你喜欢
      • 2012-05-22
      • 1970-01-01
      • 2011-05-13
      • 1970-01-01
      • 1970-01-01
      • 2020-06-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多