小编Gid*_*dle的帖子

模板部分专业化:如何避免代码重复?

当模板完全专用时,不需要复制成员函数.例如,在以下代码中,foo()只写入一次.

#include <iostream>

template<int M>   
class B
{              
public:
    void foo();   
private:
    void header();
};         

template<int M>   
void          
B<M>::foo()
{
    // specialized code:              
    header();
    // generic code:
    std::cout << "M = " << M << std::endl;             
}                   

template<int M>                                                             
void                                                                        
B<M>::header()                                                              
{                                                                           
    std::cout << "general foo()" << std::endl;                              
}                                                                           

template<>                                                                  
void                                                                        
B<2>::header()                                                              
{                                                                           
    std::cout << "special foo()" << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

但是,对于部分特化,有必要复制类定义和所有成员函数.例如:

#include <iostream>

template<int M, int N>
class A
{                  
public:   
    void foo();   
private:
    void header();
};     

template<int …
Run Code Online (Sandbox Code Playgroud)

c++ templates partial-specialization

8
推荐指数
1
解决办法
209
查看次数

标签 统计

c++ ×1

partial-specialization ×1

templates ×1