std::function参数是不允许不完整类型的。

3

我正在尝试将一个lambda表达式分配给std::function,如下所示:

std::function<void>(thrust::device_vector<float>&) f;
f = [](thrust::device_vector<float> & veh)->void
{   
    thrust::transform( veh.begin(), veh.end(), veh.begin(), tanh_f() );
};

我遇到了一个错误:
 error: incomplete type is not allowed
 error: type name is not allowed

我认为它指的是 thrust::device_vector<float>。我尝试对参数进行命名和类型定义:

typedef typename thrust::device_vector<float> vector;
std::function<void>(vector&) f;
f = [](vector & veh)->void
{   
    thrust::transform( veh.begin(), veh.end(), veh.begin(), tanh_f() );
};

毫无结果。但是,如果我只使用lambda(而不是std::function),它就可以工作:
typedef typename thrust::device_vector<float> vector;
auto f = [](vector & veh)->void
{   
    thrust::transform( veh.begin(), veh.end(), veh.begin(), tanh_f() );
};

我错过了什么吗? PS:我正在使用nvcc release 6.5,V6.5.12g++(Debian 4.8.4-1)4.8.4进行编译。
1个回答

7

您使用了错误的语法。

请尝试使用std::function<void(thrust::device_vector<float>&)> f;

std::function<void(thrust::device_vector<float>&)> f;声明了一个类型为std::function<void(thrust::device_vector<float>&)>的变量,这是一个函数对象,接受thrust::device_vector<float>&参数并返回void

g++会给出不完整类型错误,因为std::function<void>不是有效的模板实例化。

clang++会给出更好的错误信息,告诉您std::function<void>() f;是无效的变量声明:

main.cpp:11:28: error: expected '(' for function-style cast or type construction
    std::function<void>(int) f;
                        ~~~^
1 error generated.

1
@Alex 没关系,你犯了一个常见的错误,我认为这个问题和答案将有益于其他犯同样错误的人。 - Bryan Chen
这是合法的语法吗?int(int) fp; 是否声明了一个接受 int 并返回 int 的函数指针? - user253751
1
@immibis 不是;尽管int(int)是一种类型(函数类型,而不是指针类型!),但变量的声明必须使用中缀符号:(又名“用后声明”)。我们将该函数称为fp(5);因此声明必须是int(*fp)(int),其中*是必要的,以使其成为指针类型,并且括号是必要的,以防止*与返回值关联。 - M.M
类似于我们无法编写 int[5] arr; - M.M
@M.M 我也是这么想的;之前版本的回答声称 std::function<void>(thrust::device_vector<float&>) f; 是一个有效的函数指针声明。 - user253751

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接