繁体   English   中英

数组的部分模板成员专门化

[英]Partial template member specialisation for arrays

我正在尝试为不同的数据类型设置模板类:

template <typename TDataType>
class CBaseProperty : public CBasePropertyBase

现在这个类有一个像这样的数组的专门化:

template <typename TDataType, u32 TSize>
class CBaseProperty<TDataType[TSize]> : public CBasePropertyBase

现在我想为字符串编写特定成员函数的专用版本:

template <> b8 CBaseProperty<string>::setValue(const void* _pVal)

一旦我尝试为字符串数组的部分特化指定此成员:

template <u32 _TSize> b8 CBaseProperty<string[TSize]>::setValue(const void* _pVal)

我得到3个错误:

错误1错误C3860:类模板名称后面的模板参数列表必须按模板参数列表中使用的顺序列出参数

错误2错误C2995: b8 CBaseProperty<TDataType>::setValue(const void*) :函数模板已定义

错误3错误C3855: CBaseProperty<TDataType> :模板参数TDataType与声明不兼容

我究竟做错了什么? 根据我的所有资料来源,我的语法对于部分成员专业化是正确的。

谢谢你的帮助。

您只能通过提供所有模板参数 (将长度保留为参数)来专门化单个成员函数,它会强制您在此指定数组长度。

因此,如果您需要字符串数组的专用版本,将长度作为参数,则需要首先对字符串数组进行类模板的特化。

据我了解你的帖子,解决方案可以简化为以下最小的例子:

template<class T>
class foo
{
    public:
    void tell() { cout << "general\n"; }
    void base() { cout << "ok"; }
};

template<class T, std::size_t N>
class foo<T[N]>
{
    public:
    void tell() { cout << "special arrays\n"; }
};

template<std::size_t N>
class foo<std::string[N]>
{
    public:
    void tell() { cout << "special string arrays\n"; }
};

template<>
void foo<std::string>::tell()
{
  cout << "string\n";   
}

int main()
{
  foo<std::string[2]> f;   
  f.tell();

  return 0;
}

输出:

特殊字符串数组

template <u32 _TSize> b8 CBaseProperty<string[TSize]>::setValue(const void* _pVal)

当string是std :: string的别名时,这不是有效的代码,因为std :: string的长度是可变的,所以你可以在编译时专注于它的长度

template <typename TDataType, u32 TSize>
class CBaseProperty<TDataType[TSize]> : public CBasePropertyBase

这可能有用但有风险,因为什么类型的std :: size_t是实现定义的,所以如果你的u32的类型(你在评论中说的是unsigned int)与std :: size_t不同,它可能不匹配。

看实况示例: http//ideone.com/ZH4v6x

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM