我有以下 C++ 代码:
#include <cstdint>
template <typename T> class MyClass;
template <> class MyClass<int64_t> {};
int main() { MyClass<long long> obj; }
在我的 M1 MacBook 上使用 Clang 16,可以成功编译。但是在 Linux(x86 或 ARM)上使用 Clang 16 时,编译失败,并出现以下错误:
foo.cpp:4:33: error: implicit instantiation of undefined template 'MyClass<long long>'
int main() { MyClass<long long> obj; }
^
foo.cpp:2:29: note: template is declared here
template <typename T> class MyClass;
^
1 error generated.
我读过问题“long long int vs. long int vs. int64_t in C++”,但该线程正在谈论比较不同的编译器(GCC vs MSVC),而在这种情况下,它是相同的编译器(Clang 16)在相同的架构(64位ARM,或上面提到的64位x86)上,但只是不同的操作系统(Linux vs macOS)。
为什么 macOS 允许将
long long
用于 int64_t
模板,而 Linux 则不允许?
$ cat > zz.cpp
# your code
$ gcc zz.cpp
zz.cpp: In function ‘int main()’:
zz.cpp:4:33: error: aggregate ‘MyClass<long long int> obj’ has incomplete type and cannot be defined
4 | int main() { MyClass<long long> obj; }
| ^~~
$ sed -ire 's/long long/int64_t/' zz.cpp
$ gcc zz.cpp
$ ll a.out
-rwxrwxr-x 1 hannu hannu 15768 2024-11-12_21.26.01 a.out*
$ file a.out
a.out: ELF 64-bit LSB pie executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, BuildID[sha1]=121a53a4552dd1d2b1f9e3e752ef2f59cb7e0a4f, for GNU/Linux 3.2.0, not stripped
$ gcc --version
gcc (Ubuntu 13.2.0-23ubuntu4) 13.2.0
...
$ . /etc/os-release ; echo $PRETTY_NAME
Ubuntu 24.04.1 LTS