模板功能,无法弄清楚

时间:2013-04-03 13:48:20

标签: c++ templates

即使提到http://www.cplusplus.com/doc/tutorial/templates/Template Template C++ Function,我仍然不明白。

如果我有一个给定的功能,请说

week.cpp

中的

void week::writeDate (const Vector<long>& L)
week.h

中的

void writeDate (const Vector<long>& L)

我是否只在cpp和h上的函数名之前写Template <week L>? 或者它会带来更多?

或整个“周”课程本身必须是模板吗?

2 个答案:

答案 0 :(得分:1)

在week.h中

template <class T>
void writeDate (const Vector<T>& L)
{
   // code for function
}

在week.cpp

// nothing at all

这称为成员函数模板(或模板成员函数)。

答案 1 :(得分:0)

如果您想将writeDate用于任何类型的矢量。然后你必须使它成为模板功能。我看不到整个代码所以我不知道你是否在其他地方的周课堂中使用了矢量的类型,但如果你只需要writeDate那么

class week {
    // Other stuff

    template< typename T>
    void writeDate (const Vector<T>& L){
         // code goes here.
        }
// Other stuff

}

如果您的周课程以某种方式取决于矢量的类型

template < typename T>
class week {
// Other stuff

    void writeDate (const Vector<T>& L) {
     // code goes here.
    }

// Other stuff

}