方法定义中的C++模板参数

jjm*_*jjm 1 c++ templates

是否需要使用该参数声明具有模板参数的类中的所有方法声明?编译器似乎需要类似以下内容

// Queue.h
template <class ItemType>
class Queue
{
    Queue();
    ItemType dequeue();
    int count();
    /* ... other methods ... */
};
// Queue.cpp
template <class ItemType>
Queue<ItemType>::Queue()
{ /*...*/ }
template <class ItemType>
int Queue<ItemType>::count()
{/*...*/}
template <class ItemType>
ItemType Queue<ItemType>::dequeue()
{/* ... */}
Run Code Online (Sandbox Code Playgroud)

来自Java/C#,这似乎有点多余 - 我觉得我应该能够更像这样定义方法:

int Queue::count() 
Run Code Online (Sandbox Code Playgroud)

签名不引用ItemType,因此我们可以省略它.

Queue::ItemType Queue::dequeue() 
Run Code Online (Sandbox Code Playgroud)

签名引用了ItemType,但编译器知道我们正在讨论模板参数,因为我们用标识符限定了标识符 Queue::

Dav*_*eas 5

是的,您需要提供模板参数.请注意,虽然它可能看起来多余,但事实并非如此.C++模板是Java泛型的一个更强大的工具,它们允许进行特化.这意味着使用基本模板Queue可能有多个实现匹配不同的模板参数并具有不同的定义.或者,您可以Queue为一些函数创建一个具有多个特化的模板.这两种情况要求您提供template参数列表和类模板参数:

// Just member specialization
template <typename T>
struct X {
   void foo() { std::cout << "generic\n"; }
};
// specialize just this member for `int`
template <>
void X<int>::foo() { std::cout << "int\n"; }
int main() {
   X<double> xd; xd.foo();  // generic
   X<int>    xi; xi.foo();  // int
}

// Class template specialization
template <typename T>
struct X {
   void foo();
}
template <typename T>
struct X<T*> {
   void bar();
}
template <typename T>
void X<T>::foo() { std::cout << "generic\n"; }
template <typename T>
void X<T*>::bar() { std::cout << "ptr\n"; }
int main() {
   X<int > xi; xi.foo();       // generic
   X<int*> xp; xp.bar();       // ptr
}
Run Code Online (Sandbox Code Playgroud)