C++ 模板类中编写的lambda函数是否不支持restrict(…)?
最近我一直在使用amp(C++加速大规模并行)。使用此框架需要大量带有C++ 模板类中编写的lambda函数是否不支持restrict(…)?,c++,templates,lambda,c++-amp,C++,Templates,Lambda,C++ Amp,最近我一直在使用amp(C++加速大规模并行)。使用此框架需要大量带有restrict(amp)的lambda表达式。然而,当我试图在模板类中编写这些代码时,编译器抛出了一条错误消息错误C2760语法错误:意外的标记“identifier”,预期为“{'。然而,它在没有限制(amp)或模板类之外的情况下工作正常。下面是可以重现此类问题的代码: //matrix2.cpp #pragma once #include "stdafx.h" namespace rin { template
restrict(amp)
的lambda表达式。然而,当我试图在模板类中编写这些代码时,编译器抛出了一条错误消息错误C2760语法错误:意外的标记“identifier”,预期为“{'
。然而,它在没有限制(amp)
或模板类之外的情况下工作正常。下面是可以重现此类问题的代码:
//matrix2.cpp
#pragma once
#include "stdafx.h"
namespace rin
{
template <int V0, int V1>
class Matrix2
{
public:
Matrix2() : raw_(V0 * V1), view_(concurrency::extent<2>(V0, V1), raw_)
{
concurrency::parallel_for_each(concurrency::extent<2>(V0, V1),
[=](concurrency::index<2> idx)
restrict(amp)
{
});
auto fun = [=]() restrict(cpu)
{
std::cout << "It does not compile in a template class." << std::endl;
};
fun();
auto fun1 = [=]()
{
std::cout << "It does compile in a template class without the restrict(...)." << std::endl;
};
fun1();
}
std::vector<double> raw_;
concurrency::array_view<double, 2> view_;
};
}
//main.cpp
#include "stdafx.h"
#include "matrix.h"
using namespace rin;
using namespace concurrency;
int main()
{
Matrix2<5, 5> mat;
auto fun = [=]() restrict(cpu)
{
std::cout << "But outside the template class it does work!" << std::endl;
};
fun();
system("pause");
return 0;
}
//matrix2.cpp
#布拉格语一次
#包括“stdafx.h”
名称空间rin
{
模板
类矩阵2
{
公众:
Matrix2():原始(V0*V1),视图(并发::范围(V0,V1),原始)
{
并发性::并行性(concurrency::范围(V0,V1),
[=](并发::索引idx)
限制(安培)
{
});
自动乐趣=[=]()限制(cpu)
{
Std::Couth我最近遇到了这个问题。这个错误是由C++编译器选项“一致性模式”(ProjtProjksProtox:C/C++)语言引起的,它在最近的VS版本中被设置为默认启用。将这个选项设置为No,代码应该编译。
使用默认捕获是不好的做法([&]
或[=]
)类内方法。如果这些lambda将离开此上下文,并在对象被销毁后被调用,则可能会得到未定义的行为。@AlexUsachov这是一个糟糕的启发式方法。根据该逻辑,不应捕获任何具有引用或指针的内容。捕获此是lambda的一个重要方面syntax@AlexUsachov不正确。[=]
专门复制变量。[&]
可能导致悬空引用。将std::shared_ptr
和[=]
一起使用,确保类的成员在lambda超出范围之前仍然有效。