我用Google搜索并在stackoverflow C++ 11 auto compile time or runtime?中找到了解决方案。这是一个重复但不完全,答案说是编译时间。它真的是编译时间吗?让我们考虑下面的例子。
auto give_something(bool mybool)
{
if (mybool)
return string("auto");
return 6.66f;
}
int main()
{
bool mybool = (rand() % 2) ? true : false;
auto x = give_something(mybool); // how type of x is deduced?
return 0;
}
此处x
的类型和give_something
的返回类型在编译时无法推断(我的假设)。它应该仅在运行时推断。那么auto
编译时间或运行时间或两者兼而有之?
答案 0 :(得分:3)
auto
在编译时工作。
你是正确的,give_something
的返回类型不能在编译时推断出来。在这种情况下,您的代码将无法编译。 Clang为您的示例提供了此错误消息:
main.cpp:8:5: error: 'auto' in return type deduced as 'float' here but deduced
as 'std::__cxx11::basic_string<char>' in earlier return
statement
return 6.66f;