如何将类模板的成员的实现带默认参数带出类模板的边界?
How can i carry the implementation of a member of a class template with arguments by default out of boundary this class template?
我在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中的命名空间添加声明或定义,则其行为是未定义的,除非另有规定。)。
相关文章:
- 如何反转整数参数包
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 如何使用默认参数等选择模板专业化
- 模板参数替换失败,并且未完成隐式转换
- 具有默认模板参数的多态类的模板推导失败
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 函数调用中参数的顺序重要吗
- 部分定义/别名模板模板参数
- 模板-模板参数推导:三个不同的编译器三种不同的行为
- 使用不带参数的函数访问结构元素
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 如何使用Luacneneneba API正确读取字符串和表参数
- 在派生函数中指定void*参数
- 视图中的参数推导失败:take_while
- static_assert在宏中,但也可以扩展到可以用作函数参数的东西
- 定义一个带有缓冲区的函数作为卤化物中的边界框参数
- 我可以在DLL边界使用“enum class”作为函数的参数类型吗
- 如何将类模板的成员的实现带默认参数带出类模板的边界?