【发布时间】:2012-08-02 10:29:24
【问题描述】:
This answer 有这样的代码 sn-p:
template<class T, class F>
auto f(std::vector<T> v, F fun)
-> decltype( bool( fun(v[0] ) ), void() )
{
// ...
}
它确实可以编译和工作 (at least on Ideone)。
那么,这种情况下的类型是如何推导出来的呢?
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。
【问题讨论】:
-
为什么您认为它看起来无效?除了“它是有效的”之外,我真的不知道该回答什么会有所帮助。
-
@R.MartinhoFernandes 希望编辑后更清楚。问题是这里发生了什么:
decltype( bool( fun(v[0] ) ), void() )