gpt4 book ai didi

C++17类模板偏推

转载 作者:IT老高 更新时间:2023-10-28 13:00:25 25 4
gpt4 key购买 nike

我对 Template argument deduction for class templates 的理解提议是在演绎上下文中同质化模板函数和模板类的行为。但我认为我误解了一些东西。

如果我们有这个模板对象:

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 对象:

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:

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;
}

看起来类模板的模板参数推导只能推导所有参数,我希望两种行为(帮助函数和类模板)是相同的,我误解了什么吗?


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

最佳答案

来自这个优秀的trip report博通巴洛:

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类模板偏推,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41833630/

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