小编Jak*_*ker的帖子

什么是C++中用于分离标头/源的模板特化的强大方式

在中等大小甚至大型复杂项目中,分离模板声明和定义对于减少编译时间非常有用.

但是,在复杂的代码中,小程序员的错误可能会导致未被注意的行为更改,例如调用泛型版本而不是专门化.

示例:由于遗漏声明,模板专业化变得不可见.

///////////////////// file  A.hpp /////////////////////

#include <iostream>

template <typename T>

class A 
{
public:
  void foo() 
  {
      std::cerr << " calling generic foo " << std::endl ;
  }
};

// forgetting following declaration leads to an unintended program behaviour
template <> void A< int >::foo();

///////////////////// file  A-foo-int.cpp /////////////////////
#include "A.hpp"

template <> 
void A< int >::foo()
{
  std::cerr << "calling  <int> version of foo" << std::endl;
}

///////////////////// file  main.cpp /////////////////////
#include "A.hpp"

int main(int argc , …
Run Code Online (Sandbox Code Playgroud)

c++ declaration instantiation template-specialization

6
推荐指数
1
解决办法
2214
查看次数