【问题标题】:auto is not allowed here in C++ VS2017在 C++ VS2017 中不允许使用 auto
【发布时间】:2019-07-07 06:06:09
【问题描述】:
bool isEven(int val) {
    return val % 2 == 0;
}

bool isOdd(int val) {
    return val % 2 != 0;
}

template<class Iterator>
int count_function(Iterator start, Iterator end, auto criteria) {
    int count = 0;
    for (; start != end; ++start) {
        if (criteria(*start)) {
            count++;
        }
    }
    return count;
}

上面是我的代码,auto before 条件给出错误“现在允许这里自动”。我想为这个函数提供 isEven /isOdd 条件。

为什么会这样?

我尝试过 int、bool - 这会返回更多问题。

【问题讨论】:

标签: c++


【解决方案1】:

函数参数中不允许使用关键字auto。如果要使用不同的数据类型,则需要使用模板。

template<class Iterator, class T>
int count_function(Iterator start, Iterator end, T criteria) {
    int count = 0;
    for (; start != end; ++start) {
        if (criteria(*start)) {
            count++;
        }
    }
    return count;
}

【讨论】:

  • "函数参数中不允许使用关键字auto。" - 它在 lambda 函数中。
【解决方案2】:

普通函数参数中不允许使用 Auto。它只允许在 lambda 参数中使用。 C++20 将添加此功能:)

另请参阅“缩写函数模板”,此处:

https://en.cppreference.com/w/cpp/language/function_template#Abbreviated_function_template

现在,您可能会使用 lambda 声明您的函数:

auto count_function = [](auto start, auto end, auto criteria)
{
    int count = 0;
    for (; start != end; ++start) {
        if (criteria(*start)) {
            count++;
        }
    }
    return count;
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-17
    • 2017-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多