【问题标题】:Does auto deduce types in compile time or run time in C++11?在 C++11 的编译时或运行时自动推断类型吗?
【发布时间】:2016-04-18 13:44:43
【问题描述】:

我在 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 是编译时还是运行时还是两者兼而有之?

【问题讨论】:

  • Does auto deduce types in compile time or run time in C++11?: 在编译时,除了少数例外,它遵循模板参数推导规则。
  • 编译器在编译时必须知道所有类型。

标签: c++ c++11 compilation c++14


【解决方案1】:

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;

【讨论】:

  • 我没有编译和检查我的想法。
  • @jblixr 我建议下次尝试编译代码,因为你的编译器基本上会给你答案。
  • 所以使用auto 我不能从一个函数返回两种不同的类型。
  • @jblixr 不。你根本不能从一个函数返回不同的类型。
猜你喜欢
  • 2021-02-26
  • 2013-11-06
  • 1970-01-01
  • 2015-12-28
  • 2016-10-04
  • 1970-01-01
  • 2021-02-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多