为什么有时使用基本类型作为基类编译?

Ner*_*erp 4 c++ templates sfinae

编译(使用 GCC 9 和 Clang 9 测试):

template<typename U>
struct inherit : U { };

int test(inherit<int> arg);
Run Code Online (Sandbox Code Playgroud)

但这不会:

int test(inherit<int> arg) { }
Run Code Online (Sandbox Code Playgroud)

为什么第一个编译?

Nat*_*ica 6

int test(inherit<int> arg);只是一个声明。因此,我们还不需要知道inherit<int>。因此,编译器会放手。

随着int test(inherit<int> arg) { }你现在有一个定义,现在我们需要了解inherit<int>这样arg可以打掉函数退出的时候。那时模板被实例化,你得到一个错误,因为它是无效的。

忽略声明的另一个原因是,inherit稍后int可能会被专门化,并且该专门化实际上可能是一个有效的类,因为您可能有类似的东西

template<>
struct inherit<int> { };
Run Code Online (Sandbox Code Playgroud)

如果您在int test(inherit<int> arg);和之间添加它,int test(inherit<int> arg) { }那么代码现在可以编译,因为inherit<int>现在是有效类型。