轻松实施模板

fyo*_*iev 1 c++

假设我在某处编写了类模板声明collector.h:

template <class T, int maxElements>
class collector {

    T elements[maxElements];
    int activeCount;

public:

    collector();
    void process();
    void draw();

};
Run Code Online (Sandbox Code Playgroud)

并在collector.cpp以下方面实施其三种方法:

template <class T, int maxElements> 
collector<T, maxElements>::collector(){
    //code here
}

template <class T, int maxElements>
void collector<T, maxElements>::process(){
    //code here
}

template <class T, int maxElements>
void collector<T, maxElements>::draw(){
    //code here
}
Run Code Online (Sandbox Code Playgroud)

有没有办法不写作template <class T, int maxElements><T, maxElements> 每个功能的实现?像这样的东西:

template <class T, int maxElements>{

    collector<T, maxElements>::collector(){
        //code here
    }

    void collector<T, maxElements>::process(){
        //code here
    }

    void collector<T, maxElements>::draw(){
        //code here
    }

}
Run Code Online (Sandbox Code Playgroud)

Ste*_*end 5

将代码放在头文件中的类定义中.

[只要您尝试构建使用此类模板的代码,您最终可能会这样做.见这里为背景ESP.来自@Pavel Minaev的被忽视的回答.]

  • @Zac:所有使用EDG前端的编译器(例如Comeau,Intel)实现`export`.但是,那些反对`export`的人(EDG)是唯一一个实施它的供应商,后来提议将其从标准中删除.该提案通过,`export`在C++ 1x中正式弃用. (2认同)
  • 在@Pavel Minaev的帖子结尾处@ user193272的评论特别有用. (2认同)