具有模板参数和类外部默认参数的类的成员函数

Rob*_*ust 3 c++ templates class function definition

我想在模板类之外定义函数,如下所述。

已经为第二个参数尝试了很多组合,它是一个模板并且也采用默认参数。

template <typename T>
class CustomAllocator
{
 //My custom allocator
};

template <typename T, typename Allocator = CustomAllocator<T> >
class CustomContainer
{
 void push_back();
};

/*I want to define push_back outside my class, tried everything.
Almost 4 hours spent through stackoverflow, fluentcpp and all sites*/

// What should be specified for Allocator here ?
template <typename T>
void CustomContainer<T,Allocator>::push_back(T value)
{

}

//OR

template <typename T>
void CustomContainer<T,CustomAllocator<> >::push_back(T value)
{

}
Run Code Online (Sandbox Code Playgroud)

我希望它在类 Actual 之外定义,导致编译器错误,如果它是简单类型,我可以在第二个参数中轻松提及 int、float 等。

And*_*dyG 5

在类定义之外,函数不清楚类型Allocator是什么,因此您必须像重新声明一样重新声明它T

template <class T, class Allocator>
void CustomContainer<T,Allocator>::push_back(T value)
{
   // ...
}
Run Code Online (Sandbox Code Playgroud)

(我假设DataType应该是T

请注意,类中 , 的声明push_back应与定义匹配:

template <typename T, typename Allocator = CustomAllocator<T> >
class CustomContainer
{
 void push_back(T);
};
Run Code Online (Sandbox Code Playgroud)