gpt4 book ai didi

c++ - 成员声明中的模板类类型别名替换失败

转载 作者:行者123 更新时间:2023-12-03 06:53:53 25 4
gpt4 key购买 nike

假设您有一个像这样的模板化:

template <typename type>
class Object {
using length_t = unsigned int;

template <length_t length>
void put(type (&)[length]);
};

然后您像这样在其中声明了一个 put(...) 方法。如何在 class 之外声明 put(...) 方法?

  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]) {}

    但是 class 中定义的 length_t 类型别名没有被使用。

如何让第一个定义起作用,从而使 class 的特性(如类型别名)的使用在其声明和定义中保持一致,或者第二个定义是唯一的解决方案在这里?

最佳答案

How does one get the first definition to work so as to keep the use of the class's features (like type aliases) consistent across its declaration & definitions,

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

... or is the second definition the only solution here?

不,不是。如果你对 length_t 没问题不是成员(member),那么这可能会为您指明正确的方向:

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 )。 int基本情况仅供说明。如果你愿意,你仍然可以添加一个成员到 Object别名 length_t<Object> .

Live Demo

关于c++ - 成员声明中的模板类类型别名替换失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64598755/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com