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;
}
分类:
C/C++
, C/C++
/ gcc
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义