关于explicit specialization in non-namespace scope 的解决办法

关注公众号【高性能架构探索】,第一时间获取最新文章;公众号内回复【pdf】,免费获取经典书籍

经常会遇到这种场景,在类定义中,需要一个模板成员函数以及一个完全特化成员函数,所以经常会像如下这样实现:

class Base
{
public:
    template<T>
    void fun(T t) {

    }
    template <> void fun <int> (int index)  {

    }
};

会遇到如下编译错误:

explicit specialization in non-namespace scope ‘class Base’
error: template-id ‘f’ in declaration of primary template

我们可以尝试将特化版放到类外,如下:

class Base
{
public:
    template<T>
    void fun(T t) {

    }
};

template <> void base::fun<int>(int index) {

}

这样就完全没问题了

下面是一个完整例子:

#include <iostream>
#include <string>
#include <typeinfo>

class A{
public:
A(){};
template<class T>
void f(T t) {
  std::cout << "AAA" << std::endl;
}

};

template<>
void A::f<double>(double t){

  std::cout << "BBB" << std::endl;

}
int main() {
  A a;

  a.f(1);
  a.f(1.0);
  a.f('c');
}

编译并运行,输出如下:

AAA
BBB
AAA

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/1310

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2022年11月9日 下午2:12
下一篇 2022年12月6日 下午5:17

相关推荐