在模板化结构范围中使用声明进行模板化

时间:2018-07-22 18:16:26

标签: c++ templates types

我已经做了一个结构来从列表中检索类型,可以这么说。此版本编译。

template<uint16_t index, class first, class...rest>
struct type_at {

    type_at() = delete;

    static constexpr inline auto create() {
        if constexpr(index == 0) {
            struct conditional {
                constexpr inline conditional() = default;
                using type = first;
            }; return conditional();}
        else {
            struct conditional {
                constexpr inline conditional() = default;
                using type = typename type_at<index - 1, rest...>::type;
            }; return conditional();}
    }

    using type = typename decltype(create())::type;
};

在实施过程中,我制作了一个新版本,将索引模板参数移动到“类型”和“创建”,就像这样。

template<class first, class...rest>
struct type_at {

    type_at() = delete;

    template<uint16_t index>
    static constexpr inline auto create() {
        if constexpr(index == 0) {
            struct conditional {
                constexpr inline conditional() = default;
                using type = first;
            }; return conditional();}
        else {
            struct conditional {
                constexpr inline conditional() = default;
                using type = typename type_at<rest...>::type<index - 1>;
            }; return conditional();}
    }

    template<uint16_t index>
    using type = typename decltype(create<index>())::type;
};

此版本因在create()中访问结构类型(expected ; before < token)的编译错误...type<index - 1>;而失败。

我的问题是:为什么?对我而言,为什么编译器不会期望模板参数并不明显。我尝试了type.template,但这没有帮助。我猜想我缺少了一些东西,所以任何帮助的理解将不胜感激。

1 个答案:

答案 0 :(得分:1)

您确实需要。模板

但是,由于您没有实例,因此它必须为::,就像静态方法一样。

->send(xx, "UNIQUE_MESSAGE", strlen("UNIQUE_MESSAGE"), 0);