【问题标题】:How to use auto keyword in argument list in C++ 11?如何在 C++ 11 的参数列表中使用 auto 关键字?
【发布时间】:2021-11-04 14:27:39
【问题描述】:

当函数调用多个类型参数时,如何替换函数参数中的 auto 关键字?因为我想使用-std=c++11,而我在 omnet++ 中遇到了这个错误:

**error: use of auto in parameter declaration only available with -std=c++14 or -std=gnu++14**  
void get_index(auto s_arra[], auto elem) {
    ...
}

void main() {
    get_index(float array1, float var1);
    get_index(int array2, int var2);
}

【问题讨论】:

  • 您切换到使用 C++20 之前的模板。
  • auto 在函数声明中是 C++20,而不是 C++14。通用 lambda 虽然是 C++14。 gcc 错误消息在这里具有误导性。
  • 既然你传递float数组和值,使用float而不是auto?或者,如果您希望函数更通用,那么可能是模板?
  • 制作模板
  • 你不能在函数参数前加上float这样的类型名称。

标签: c++ auto


【解决方案1】:
void get_index(auto s_arra[], auto elem) {
    //...
}

仅在 C++20 中有效(gcc 错误消息具有误导性)

以前,您使用模板的方式很冗长

template <typename T1, typename T2>
void get_index(T1 s_arra[], T2 elem) {
    //...
}

可能他们使用相同的类型,所以

template <typename T>
void get_index(T s_arra[], T elem) {
    //...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-24
    • 2023-03-31
    • 2021-02-18
    • 2011-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-14
    相关资源
    最近更新 更多