我正在尝试使用
extern template
来减少项目中的编译时间。特别是,我想最小化类构造函数的实例化。
这是示例代码:
#include <iostream>
namespace Hello {
class Test {
template<typename T>
Test(T& t) {
std::cout << t << std::endl;
}
};
}
extern template Hello::Test::Test<int>(int&);
编译此 Clang 时,出现以下错误:
> <source>:13:30: error: qualified reference to 'Test' is a constructor name rather than a type in this context
13 | extern template Hello::Test::Test<int>(int&);
> | ^
<source>:13:34: error: expected unqualified-id
13 | extern template Hello::Test::Test<int>(int&);
> | ^
2 errors generated. Compiler returned: 1
但是,它可以使用 GCC 编译良好:https://godbolt.org/z/61M3zxsE3。
这是怎么回事?
应该无需显式设置模板参数:
extern template Hello::Test::Test(int&);
这是因为构造函数模板参数无法显式设置,只能从参数中推导出来:
int n = 0;
auto t1 = Hello::Test<int>(n); // error
auto t2 = Hello::Test(n); // ok