7

Q1:命名空间范围内是否允许用户定义的推导指南?

在此处的示例中,GCC 和 Clang 不会产生相同的行为:

#include <tuple>

template <typename T>
struct some_type;
template <template <typename...> typename T, typename ... Ts>
struct some_type<T<Ts...>>
{
    template <typename U>
    class nested
    {
        U member;
    public:
        nested(U &&){}
    };

    // non-namespace scope user-deduction-guide : OK with Clang, fix the deduction issue
    template <typename U>
    nested(U&&) -> nested<U>;
};

void func()
{
    using pack_type = std::tuple<int, char>;
    some_type<pack_type>::nested{
        [](auto &&){}
    };
}

简而言之,我们有一个模板参数类型,嵌套类型本身就是模板参数,模板参数之间没有任何关系。

template <typename T>
struct some_type;
template <template <typename...> typename T, typename ... Ts>
struct some_type<T<Ts...>>
{
    template <typename U>
    class nested // <- nested type, where `U` as no relationship with `T<Ts...>`
    {
        U member;
    public:
        nested(U &&);
    };
};

标准规定:http ://eel.is/c++draft/temp.deduct.guide#3

[...]演绎指南应在与相应类模板相同的范围内声明,并且对于成员类模板,具有相同的访问权限。[...]

Q2:如果Q1没有,当namespace-type和nested-type template-parameters之间没有关系时,创建嵌套类型的自定义推导指南的语法是什么?

我希望语法接近:

template <template <typename...> typename T, typename ... Ts>
template <typename U>
some_type<T<Ts...>>::nested<U>::nested(U&&) -> nested<U>;

然而,这nested<U>错误的,因为它需要一个推导的类型......来推导它。

此外,这被解释为具有尾随返回类型的函数void

template <template <typename...> typename T, typename ... Ts>
template <typename U>
typename some_type<T<Ts...>>::template nested<U>::nested(U&&) -> nested<U>;

谢谢你的时间。

4

1 回答 1

0

快速解决

user-defined deduction guide我发现的唯一解决方法是为 Clang添加一个only,
这在可维护性方面是次优的。

Godbolt 上的实时示例
或查看以下来源

为什么 ?

  • GCC不允许在非命名空间上下文中进行推导,Clang允许。
  • Clang在这种情况下需要推导指南,GCC不需要

注意:发布此消息时,clang 主干是 11.0.1,而 gcc 主干是 10.2

#include <tuple>

template <typename T>
struct type
{
    template <typename U>
    struct nested
    {
        template <typename ... nested_Ts>
        nested(U &&, std::tuple<nested_Ts...> &&)
        {}

    };
    #if __clang__
    // here, user-defined deduction guide only for Clang
    template <typename U, typename ... Ts>
    nested(U&&, std::tuple<Ts...>&&) -> nested<U>;
    #endif
};

void instanciate_symbols()
{
    using type = type<int>;
    [[maybe_unused]] auto value = type::nested{'a', std::tuple{42, .42f}};
}
于 2021-03-31T12:36:21.847 回答