模板类类型别名在成员声明中无法替换

2024-04-03

假设你有一个模板class像这样:

template <typename type>
class Object {
  using length_t = unsigned int;
  
  template <length_t length>
  void put(type (&)[length]);
};

你宣布了put(...)方法就像这样。 你如何声明这一点put(...)方法之外的class?

  1. 这是有人可能采取的一种方法:

    /* 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])
    
  2. 这是声明的另一种方式put(...)方法使其有效:

    /* SUCCESS: But `length_t` alias isn't used */
    template <typename type>
    template <unsigned int length>
    void Object<type>::put(type (&)[length]) {}
    

    but the length_t类型别名定义在class没有被使用。

如何使第一个定义发挥作用,以便继续使用class的功能(如类型别名)在其声明和定义中保持一致,或者第二个定义是这里唯一的解决方案?


如何使第一个定义起作用,以便在其声明和定义中保持类功能(如类型别名)的使用一致,

我必须承认我不理解这个错误,也不知道如何通过仅更改定义来修复它。错误消息相当令人困惑(您应该将其包含在问题中)。

...或者第二个定义是这里唯一的解决方案?

不它不是。如果你愿意拥有length_t如果不是会员,那么这可能会为您指明正确的方向:

template <template<typename> typename T>
struct length { using type = int; };

template <template<typename> typename T>
using length_t = typename length<T>::type;


template <typename> struct Object;
template <> struct length<Object> { using type = unsigned int; };

template <typename type>
class Object {
  //using length_t = unsigned int;
  
  template <length_t<Object> length>
  void put(type (&)[length]);
};

template <typename type>
template <length_t<Object> length>
void Object<type>::put(type (&)[length]) {}

length是一个“模板特征”(不确定这个术语是否真的存在)。而不是有length_t作为成员Object你需要提供专业化length<Object>(这需要提前声明Object). The int基本情况仅用于说明。如果您愿意,您仍然可以添加会员Object别名length_t<Object>.

现场演示 https://godbolt.org/z/cocMW7

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

模板类类型别名在成员声明中无法替换 的相关文章

随机推荐