这个答案 https://stackoverflow.com/a/11774533/476681有这样的代码片段:
template<class T, class F>
auto f(std::vector<T> v, F fun)
-> decltype( bool( fun(v[0] ) ), void() )
{
// ...
}
它确实可以编译并工作(至少在 Ideone 上 http://ideone.com/dhyxN).
那么,这种情况下类型是如何推导的呢?
c++11 标准真的允许下一行吗?
decltype( bool( fun(v[0] ) ), void() )
我快速浏览了一下,看起来不太有效。在这种情况下,ideone 错了吗?
c++11 标准中的所有示例都在 decltype 中只有一种类型:
struct A {
char g();
template<class T> auto f(T t) -> decltype(t + g())
{ return t + g(); }
};
另一个例子 :
void f3() {
float x, &r = x;
[=] {
decltype(x) y1;
decltype((x)) y2 = y1;
decltype(r) r1 = y1;
decltype((r)) r2 = y2;
};
和另一个
const int&& foo();
int i;
struct A { double x; };
const A* a = new A();
decltype(foo()) x1 = i;
decltype(i) x2;
decltype(a->x) x3;
decltype((a->x)) x4 = x3;
它们在 decltype 中都只有一个参数。为什么上面的代码有两个参数(用逗号分隔)?
我创建了另一个示例(无法编译):
#include <vector>
#include <iostream>
template<class T, class F>
auto f(std::vector<T> v, F fun) -> decltype(bool(fun(v[0])), void())
{
// ...
(void)v;(void)fun;
return fun(v.size());
}
void ops(int)
{
}
int main(){
std::vector<int> v;
f(v, [](int){ return true; });
f(v,ops);
}
即使线f(v,ops);
被删除时,返回类型f
模板函数被评估为 void。