C ++ 17类模板部分推导 [英] C++17 class template partial deduction

查看:125
本文介绍了C ++ 17类模板部分推导的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 模板的理解类模板的参数推导 提议是在推导上下文中使模板函数和模板类的行为同质。但是我认为我误会了一些东西。

My understanding about the Template argument deduction for class templates proposal was to homogenize the behaviour of template functions and template classes in deduction contexts. But I think that I have misunderstood something.

如果我们有此模板对象:

If we have this template object:

template <std::size_t S, typename T>
struct test
{
    static constexpr auto size = S;
    using type_t = T;

    test(type_t (&input)[size]) : data(input) {}
    type_t (&data)[size]{};
};

我倾向于使用辅助功能作为语法糖来创建 test 对象:

I tend to use a helper function as syntactic sugar for creating test objects:

template <std::size_t S, typename T>
test<S, T> helper(T (&input)[S]) { return input; }

可以使用如下所示:

int main()
{
    int buffer[5];

    auto a = helper<5, int>(buffer); // No deduction
    auto b = helper<5>(buffer);      // Type deduced
    auto c = helper(buffer);         // Type and size deduced

    std::cout << a.size << b.size << c.size;

    return 0;
}

上面的代码输出 555 符合预期。我已经在Wandbox中使用较新的编译器设置进行了相同的尝试 1

The code above outputs 555 as expected. I've tried the same in Wandbox using the newer compiler setup1:

int main()
{
    int buffer[5];

    test<5, int> a(buffer); // No deduction: Ok.
    test<5> b(buffer);      // Type deduced: FAILS.
    test c(buffer);         // Type and size deduced: Ok.

    std::cout << a.size << b.size << c.size;

    return 0;
}

看起来,类模板的模板参数推导只能推导所有参数,我期望两个行为(辅助函数和类模板)都相同,我是否误解了?

It looks like template argument deduction for class templates works only deducing all the parameters, I was expecting both behaviours (helper function and class template) to be the same, did I misunderstood something?

1 Wandbox中最新可用的编译器是 gcc HEAD 7.0.1 201701 clang HEAD 5.0.0(trunk)

1The last compilers availables in Wandbox are gcc HEAD 7.0.1 201701 and clang HEAD 5.0.0 (trunk).

推荐答案

来自这个出色的旅行报告,作者:Botond Ballo:

From this excellent trip report by Botond Ballo:


最初提出的功能包括部分扣除的规定,您可以在其中明确指定一些模板参数,而其余部分则要扣除,但这是出于担心在某些情况下可能会造成混淆的担忧:

The feature as originally proposed included a provision for partial deduction, where you explicitly specify some of the template arguments, and leave the rest to be deduced, but this was pulled over concerns that it can be very confusing in some cases:

// Would have deduced tuple<int, string, float>,
// but tuple<int> is a well-formed type in and of itself!
tuple<int> t(42, "waldo", 2.0f);


这篇关于C ++ 17类模板部分推导的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆