如果您没有源代码,请在 C++14 中进行类型推导
Type deduction in C++14 if you don't have the source
使用 C++14 中新的 return 类型推导,您可以编写如下代码:
auto almostPi (void) { return 3.14159; }
并且函数本身将使用 return 值来决定函数的 actual return 类型,在本例中为 double
.
对于没有源代码,而只有包含如下内容的头文件的通用库,这是如何做到的:
auto almostPi (void);
在这种情况下,编译器如何知道在您这样做时警告您:
char *dodgyPointer = almostPi();
来自您自己的代码。
如果无法推导出 return 类型,则无法调用该函数:
$ cat test.cpp
auto almostPi(void);
void test() {
char *dodgyPointer = almostPi();
}
$ g++ -c test.cpp --std=c++14
test.cpp: In function ‘void test()’:
test.cpp:4:24: error: use of ‘auto almostPi()’ before deduction of ‘auto’
char *dodgyPointer = almostPi();
^
库只需要在其 header 中声明实际的 return 类型。
使用 C++14 中新的 return 类型推导,您可以编写如下代码:
auto almostPi (void) { return 3.14159; }
并且函数本身将使用 return 值来决定函数的 actual return 类型,在本例中为 double
.
对于没有源代码,而只有包含如下内容的头文件的通用库,这是如何做到的:
auto almostPi (void);
在这种情况下,编译器如何知道在您这样做时警告您:
char *dodgyPointer = almostPi();
来自您自己的代码。
如果无法推导出 return 类型,则无法调用该函数:
$ cat test.cpp
auto almostPi(void);
void test() {
char *dodgyPointer = almostPi();
}
$ g++ -c test.cpp --std=c++14
test.cpp: In function ‘void test()’:
test.cpp:4:24: error: use of ‘auto almostPi()’ before deduction of ‘auto’
char *dodgyPointer = almostPi();
^
库只需要在其 header 中声明实际的 return 类型。