将外部模板与类构造函数一起使用

问题描述 投票:0回答:1

我正在尝试使用

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

这是怎么回事?

c++ templates
1个回答
0
投票

应该无需显式设置模板参数:

extern template Hello::Test::Test(int&);

这是因为构造函数模板参数无法显式设置,只能从参数中推导出来:

int n = 0;
auto t1 = Hello::Test<int>(n);  // error
auto t2 = Hello::Test(n);       // ok
© www.soinside.com 2019 - 2024. All rights reserved.