跟进我的问题c++ - 使用中间类型时隐式转换如何工作?,从中我了解了1 隐式转换 max的规则,我试图了解涉及函数参数的更高级用例。
假设我有一个函数,它接受另一个函数作为参数。该函数参数可以返回某些内容,也可以不返回任何内容(void)。因此,我想重载函数定义,在一种情况下接受非 void 函数参数,在另一种情况下接受 void 函数参数。
using VoidType = void (string);
using NonVoidType = string (string);
string call(VoidType *fn, string arg) {
cout << "[using void function]" << endl;
fn(arg);
return arg;
}
string call(NonVoidType *fn, string arg) {
cout << "[using non void function]" << endl;
return fn(arg);
}
Run Code Online (Sandbox Code Playgroud)
调用函数时,给定参数具有已知类型,因此重载选择应该很简单,如下所示:
void printVoid(string message) {
cout << message << endl;
}
string printNonVoid(string message) {
cout << message << endl;
return message;
} …Run Code Online (Sandbox Code Playgroud)