C++不同标准兼容性问题集
- 特化模板兼容性
下列代码在 c++17 及之前都是可以的,但从 c++20 开始编译报语法错误:
// g++ -g -std=c++20 -o x x.cpp;./x
#include <stdio.h>
#include <string>
template <class type>
struct X {
X(type t) { this->t = t; }
type t;
};
template <>
struct X<int> {
X<int>(int t) { this->t = t; }
int t;
};
int main() {
X<int> x(2);
printf("%d, %d\n", __cplusplus, x.t);
return 0;
}
# g++ -g -std=c++17 -o x x.cpp;./x
201703, 2
用 c++20、c++23 编译报的语法错误:
# g++ -g -std=c++20 -o x x.cpp;./x
x.cpp:13:16: error: expected unqualified-id before ‘int’
13 | X<int>(int t) { this->t = t; }
| ^~~
x.cpp:13:16: error: expected ‘)’ before ‘int’
13 | X<int>(int t) { this->t = t; }
| ~^~~
| )
从 c++20 开始需要改成(同时适用 C++17 及之前的标准):
// g++ -g -std=c++20 -o x x.cpp;./x
#include <stdio.h>
#include <string>
template <class type>
struct X {
X(type t) { this->t = t; }
type t;
};
template <>
struct X<int> {
X(int t) { this->t = t; } // X<int>(int t) 改成 X(int t)
int t;
};
int main() {
X<int> x(2);
printf("%d, %d\n", __cplusplus, x.t);
return 0;
}