gpt4 book ai didi

c++ - 在 lambda 表达式中使用模板类方法时出现 GCC 编译错误

转载 作者:太空狗 更新时间:2023-10-29 21:02:13 25 4
gpt4 key购买 nike

以下代码在 gcc 4.6.3 中编译失败,而在 clang 3.1 中编译完美(我提供了两个版本的 DummyMath 类,都出现了同样的问题):

#include <iostream>
using namespace std;

//* // To swap versions, comment the first slash.

// ===============================================
// V1
// ===============================================
template <typename T>
class DummyMath
{
public:
T sum(T a1, T a2);
T mult(T a1, int n);
};

template <typename T>
T DummyMath<T>::sum(T a1, T a2)
{
return a1 + a2;
}

template <typename T>
T DummyMath<T>::mult(T a1, int n)
{
auto x2 = [this](T a1) -> T
{
return sum(a1, a1); // <------- gcc will say that "sum" was not declared in this scope!
};

T result = 0;
n = n/2;
for(int i = 0; i < n; ++i)
result += x2(a1);
return result;
}
/*/
// ===============================================
// V2
// ===============================================
template <typename T>
class DummyMath
{
public:
T sum(T a1, T a2)
{
return a1 + a2;
}

T mult(T a1, int n)
{
auto x2 = [this](T a1) -> T {
return sum(a1, a1);
};

T result = 0;
n = n/2;
for(int i = 0; i < n; ++i)
result += x2(a1);
return result;
}
};
//*/

int main()
{
DummyMath<float> math;
cout << math.mult(2.f, 4) << endl;

return 0;
}

错误是:

main.cpp:25:20: error: ‘sum’ was not declared in this scope

类 DummyMath 的两个版本(V1 和 V2)在 gcc 中都失败了,但在 clang 中都成功了。这是 GCC 中的错误吗?

谢谢。

最佳答案

这是 gcc 4.7.2 中的已知错误(参见 question)。编译器识别出 this 指针将被捕获,并且生成的闭包确实包含它的指针,但该指针未在闭包的构造函数中初始化。

您可以使用 return this->sum(a1, a2); 让它工作。在 LiveWorkSpace 上运行您的示例, 表明这对于 gcc >= 4.7.3 以及 Clang 3.2 和 Intel 13.0.1 是固定的(即打印 8 作为输出)。

C++11 支持不断变化,最好尽快升级到您最喜欢的编译器的最新版本。不幸的是,大多数 Linux 发行版都提供了 gcc 4.7.2 的打包版本,而 gcc 4.8.0 还没有。您可能需要从源代码编译它们。

关于c++ - 在 lambda 表达式中使用模板类方法时出现 GCC 编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16007855/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com