【发布时间】:2020-10-29 20:25:50
【问题描述】:
假设您有一个这样的模板class:
template <typename type>
class Object {
using length_t = unsigned int;
template <length_t length>
void put(type (&)[length]);
};
你在其中声明了一个put(...) 方法,就像这样。
您如何在 class 之外声明 put(...) 方法?
-
这是某人可能采取的一种方法:
/* ERROR: Doesn't match any declarations(?) */ template <typename type> template <typename Object<type>::length_t length> void Object<type>::put(type (&)[length]) {}但这会导致一个特殊的错误
error: no declaration matches 'void Object<type>::put(type (&)[length])' note: candidate is: template <class type> template <unsigned int length> void Object<type>::put(type (&)[length]) -
这是声明
put(...)方法的另一种方法,以便它可以工作:/* SUCCESS: But `length_t` alias isn't used */ template <typename type> template <unsigned int length> void Object<type>::put(type (&)[length]) {}但是
class中定义的length_t类型别名没有被使用。
如何让第一个定义起作用,以便在其声明和定义中保持class 的特性(如类型别名)的使用一致,或者第二个定义是这里唯一的解决方案?
【问题讨论】:
-
因此,在现代 C++ 代码中可能存在一些不常见或不被接受的代码示例的设计/样式选择,但我想声明提出的问题仍然存在,尽管对如何代码看起来或它的功能是什么。
-
没关系。不过,您可以将该免责声明添加到问题本身,而不是作为评论。
-
是
lenght_t作为类型特征而不是成员别名的选项吗?我想不会,你不想改变类的声明 -
人们如何回答或查看它与他们的回答方式有关;)
-
我知道,这就是我在问题中读到的内容。但是将
lenght_t不作为成员而是作为类型特征是否可以接受?而不是Object<T>::lenght_t,它将类似于length_t<T>或length_t<Object<T>>
标签: c++ class templates alias declaration