class 的成员函数,模板参数和默认参数在 class 之外

Member function of class with template arguments and default arguments outside class

我想在模板外定义函数 class 如下所述。

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

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 Whosebug, 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)
{

}

我希望它在 class 之外定义 实际得到编译器错误,如果它是简单类型,我可以很容易地在第二个参数中提到 int、float 等。

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

template <class T, class Allocator>
void CustomContainer<T,Allocator>::push_back(T value)
{
   // ...
}

(我假设 DataType 应该是 T

请注意,您在 class 中对 push_back 的声明应与定义相匹配:

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

您不能对在模板定义之外定义的模板成员函数使用默认模板参数。

来自 C++ 17 标准(17.1 模板参数)

  1. ... A default template-argument shall not be specified in the template- parameter-lists of the definition of a member of a class template that appears outside of the member’s class.

所以只写

template <typename T, typename Allocator>
void CustomContainer<T, Allocator>::push_back( const T &value )
{
    //...
}

注意函数的参数。您的函数声明与其定义不符。