23

gcc 4.9 允许以下代码,但 gcc 4.8 和 clang 3.5.0 拒绝它。

void foo(auto c)
{
    std::cout << c.c_str();
}

我进入warning: ISO C++ forbids use of 'auto' in parameter declaration [-Wpedantic]4.9 但在 4.8 和 clang 我得到了error: parameter declared 'auto'.

4

2 回答 2

18

是的,这是一个扩展。我相信,它可能会作为“概念”提案的一部分添加到 C++17 中。

于 2014-09-16T23:03:52.877 回答
11

这是 Concepts Lite 的代言人

template<class T>
void foo(T c)
{
    std::cout << c.c_str();
}

auto只是替换了更详细的template<class T>。同样,你可以写

void foo(Sortable c)

作为简写

template<class T> 
requires Sortable<T>{}
void foo(T c)

这里,Sortable是一个概念,它被实现为谓词的结合,这些constexpr谓词形式化了对模板参数的要求。检查这些要求是在名称查找期间完成的。

从这个意义上说,auto是一个完全不受约束的模板。

于 2014-09-17T09:35:28.980 回答