欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

specialization of xxx after instantiation

最编程 2024-07-16 18:31:55
...

编译出现这个错误,原因是特化模板放到模板调用后面了。

如果特化的定义在使用模板之后出现,编译器将无法正确地实例化特化。

下面是正常能编译过的:

template <typename T>
void foo(T value) {
    // 模板函数的定义
}

template<>
void foo<int>(int value) {
    // int 类型的特化定义
}

int main() {
    foo(42);
}

下面是编译会出错的:

template <typename T>
void foo(T value) {
    // 模板函数的定义
}

int main() {
    foo(42);
}

template<>
void foo<int>(int value) {
    // int 类型的特化定义
}

出错提示:

/home/user/work/testdir/a.cpp:11:24: error: specialization of ‘void foo(T) [with T = int]’ after instantiation
   11 | void foo<int>(int value) {
      |                        ^

这个有时跟编译选项有关,release编译有这个问题,debug没有。

我遇到这个是因为Qt的一个模板特化是用宏提供的,这个宏在代码里调用了,而这个宏前面有使用这个模板,所以Release编译报错。

解决方法,把这个宏调用放到c++最前面,或加到头文件里,保证这个特化的模板使用前已经定义。