如何将类模板的成员的实现带默认参数带出类模板的边界?

How can i carry the implementation of a member of a class template with arguments by default out of boundary this class template?

本文关键字:参数 边界 默认 成员 实现      更新时间:2023-10-16

我在VS 2010工作。我正在尝试扩展功能并重新定义multimap容器的任何功能:

// test_multimap.h
#include <map>
namespace std
{
     template <typename TKey, typename TData, 
            class Compare = less<TKey>,
            class Alloc = allocator<pair<const TKey, TData>>
            >
     class test_multimap: public multimap<TKey, TData, Compare, Alloc>
     {
     public:
         void clear()
         {
             multimap<TKey, TData>::clear();
         }
         /*...*/

这是可行的,但是如果我尝试执行成员函数的实现,就会遇到一些问题:

// test_multimap.h
#include <map>
namespace std
{
    template <typename TKey, typename TData, 
              class Compare = less<TKey>,
              class Alloc = allocator<pair<const TKey, TData>>
         >
    class test_multimap: public multimap<TKey, TData, Compare, Alloc>
    {
    public:
        void clear();
        /*...*/

// test_multimap.cpp
#include "stdafx.h"
#include "test_multimap.h"
namespace std
{
    template <typename TKey, typename TData,
              class Compare = less<TKey>,
              class Alloc = allocator<pair<const TKey, TData>>
             >
    void test_multimap<TKey, TData, Compare, Alloc>::clear()
    {
        multimap<TKey, TData>::clear();
    }
 }

在这种情况下,我得到错误

C4519(默认情况下模板参数只能在类模板中使用)在其他情况下,我得到一组不同的错误。

如何实现模板成员函数??

只要按照错误提示做:在定义函数时不要使用默认值,你就会没事的。

namespace std
{
    template <typename TKey, typename TData,
              class Compare,
              class Alloc
             >
    void test_multimap<TKey, TData, Compare, Alloc>::clear()
    {
        multimap<TKey, TData>::clear();
    }
}

你的代码还有两个问题:

  • 正如JBL在他的评论中所说,从STL容器继承不是一个好主意,因为它们没有虚拟析构函数。您的test_multimap将出现工作,但一旦有人试图多态地使用它并通过基类指针删除test_multimap,他将遇到未定义的行为。
  • 标准禁止向std命名空间添加类(§17.6.4.2.1/1:如果c++程序向命名空间std或命名空间std中的命名空间添加声明或定义,则其行为是未定义的,除非另有规定。)。