Reputation: 11008
This post already explains how adding deduction guides in the std namespace is undefined.
Now, what I would really like to do is this:
namespace std { // undefined behavior
template <class... U>
array(char const*, U...) -> array<string, 1 + sizeof...(U)>;
}
So this is what I've tried:
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)>;
And it works
auto const arr = array{ "hello", "world" };
// array<std::string, 2ul>
My question now is:
Q: Is this my only option for adding deduction guides for stl types? Are there other options?
Upvotes: 3
Views: 171
Reputation: 303217
Is this my only option for adding deduction guides for stl types?
Yes - in the sense that what you did was not adding a deduction guide for a type in the standard library, it was adding a deduction guide for your own type (that happens to inherit from a standard library type). You can always add deduction guides to your own types.
Are there other options?
This doesn't have to use CTAD. You could also write a function:
auto const arr = make_array("hello", "world");
Such that make_array
gives you an std::array<T, N>
where T
is the decayed type of the first element or, if that type is char const*
, string
instead.
Upvotes: 2