gpt4 book ai didi

c++ - 为 STL 类型添加推导指南有哪些选项

转载 作者:行者123 更新时间:2023-12-02 05:55:25 25 4
gpt4 key购买 nike

This帖子已经解释了如何在 std 命名空间中添加推导指南是未定义的。
现在,我真正想做的是:

namespace std { // undefined behavior
template <class... U>
array(char const*, U...) -> array<string, 1 + sizeof...(U)>;
}

这就是我尝试过的:

template <typename T, std::size_t N>
struct array : std::array<T, N> {};

template <class... U>
array(char const*, U...) -> array<std::string, 1 + sizeof...(U)>;

template <typename T, class... U>
array(T, U...) -> array<T, 1 + sizeof...(U)>;

而且它有效

auto const arr = array{ "hello", "world" };
// array<std::string, 2ul>

我现在的问题是:
问:这是我为 STL 类型添加推导指南的唯一选择吗?还有其他选择吗?

最佳答案

Is this my only option for adding deduction guides for stl types?

是的 - 从某种意义上说,您所做的并不是为标准库中的类型添加推导指南,而是为您自己的类型(恰好继承自标准库类型)添加推导指南。您随时可以为自己的类型添加推导指南。

Are there other options?

不必使用CTAD。您还可以编写一个函数:

auto const arr = make_array("hello", "world");

这样make_array给你一个std::array<T, N>哪里T是第一个元素的衰减类型,或者,如果该类型是 char const* , string相反。

关于c++ - 为 STL 类型添加推导指南有哪些选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59949060/

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