【发布时间】:2016-12-20 12:31:55
【问题描述】:
以下代码:
typedef void HELPER;
const HELPER* helper = _helper;
inline ostream& operator <<(ostream& out, const HELPER* arg)
{ out << (const char*)(arg); return out; }
如果我尝试了就会爆炸
cout << helper;
具体来说,我得到:
main.cpp:35:28:错误:使用重载运算符“”和“const HELPER *”(又名“const void *”))
它列出了一些候选人:
/Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/ostream:207:0: note: candidate function
basic_ostream& operator<<(const void* __p);
^
main.cpp:25:17: note: candidate function
inline ostream& operator <<(ostream& out, const HELPER* arg)
^
/Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/ostream:195:20: note: candidate function
basic_ostream& operator<<(bool __n);
^
我有点惊讶我的 typedef 没有在这里调用更强的类型匹配。我怎样才能让这个运算符重载运行?
编辑:进一步澄清,这段代码的目的是我双重定位一组 Arduino 库。他们经常通过以下方式管理他们的字符串:
typedef void __FlashStringHelper;
void showHelp(const __FlashStringHelper* helpText)
{
Serial.print(helpText);
}
我喜欢 iostream 并计划在这个双重目标上,所以我在 Serial 对象上重载
#define cout Serial
void showHelp(const __FlashStringHelper* helpText)
{
cout << helpText;
}
现在我想将真正的 iostream 实际定位为不同的拱门,但旧的 Arduino 代码与其 __FlashStringHelpers 没有太大的不同。这就是我所在的地方
【问题讨论】:
-
您的符号
HELPER基本上只是void的别名。因此,const void*(您的和标准的)有两个重载,而且指针可以隐式转换为bool,从而为您提供第三种选择。 -
typedef 没有引入新类型。
-
您希望通过显示的解决方案解决的实际问题是什么?你为什么做了这样的超载?它的目的是什么?也许我们可以帮你解决这个问题?请参阅有关the XY problem 的一些相关阅读。
-
谢谢大家,它现在可以工作了!