【问题标题】:error using auto: does not name a type, c++ version of numpy's arange使用 auto 时出错:没有命名类型,numpy 的 arange 的 c++ 版本
【发布时间】:2015-10-13 00:04:58
【问题描述】:

寻找在c++中实现numpyarange函数的代码,找到了this answer

我将以下代码放在一个文件test_arange_c.cpp

#include <vector>

template<typename T>
std::vector<T> arange(T start, T stop, T step = 1)
{
  std::vector<T> values;
  for (T value = start; value < stop; value += step)
    values.push_back(value);
  return values;
}

int main()
{
  double dt;
  dt = 0.5;
  auto t_array = arange<double>(0, 40, dt);
  return 0;
}

当我尝试编译它时,我收到以下错误:

$ c++ test_arange_c.cpp -o test_arange_c.out
test_arange_c.cpp: In function ‘int main()’:
test_arange_c.cpp:14:8: error: ‘t_array’ does not name a type
   auto t_array = arange<double>(0, 40, dt);

毫无疑问,我犯了一个对于经验丰富的 c++ 用户来说显而易见的错误。但是,在谷歌搜索了一段时间后,我没有想出它是什么。

【问题讨论】:

  • 您似乎没有启用 C++11 支持,或者您的编译器没有它。
  • @Brian 有没有简单的方法来检查这个?报告我的编译器版本会告诉你情况是否如此吗?
  • 您可以使用 __cplusplus 宏检查是否为给定编译启用了 C++11。 stackoverflow.com/questions/5047971/…
  • 如果你想知道你的编译器是否实现了C++11,你应该查阅文档。
  • @Brian 究竟是什么关键字在这里需要 C++11? (我想更改问题标题,以便将来使用此关键字出现此错误的人更容易找到解决方案。)

标签: c++ templates vector auto typename


【解决方案1】:

正如@Brian 建议的那样,我没有启用C++11 支持。

$ c++ --version
c++ (Ubuntu 4.8.4-2ubuntu1~14.04) 4.8.4
Copyright (C) 2013 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

这失败了:

$ c++ test_arange_c.cpp -o test_arange_c.out
test_arange_c.cpp: In function ‘int main()’:
test_arange_c.cpp:16:8: error: ‘t_array’ does not name a type
   auto t_array = arange<double>(0, 40, dt);
        ^

这行得通:

$ c++ -std=c++11 test_arange_c.cpp -o test_arange_c.out
$

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-19
    • 1970-01-01
    • 2015-12-01
    • 1970-01-01
    • 2021-02-01
    • 1970-01-01
    相关资源
    最近更新 更多