以下代码在 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 中的错误吗?
谢谢。