smeikx
smeikx

Reputation: 23

How to write a deduction guide for passing anonymous std::array of variable size?

I want to be able to pass an anonymous std::array of variable size to a constructor:

using namespace std;

template <size_t N>
struct A
{
    array<string, N> const value;
    A (array<string, N>&& v): value {v} {}
};

Trying to pass an anonymous array like this …

A a { { "hello", "there" } };

This results in the following error (using clang++):

error: no viable constructor or deduction guide for deduction of template arguments of 'A'

If I don’t use a template and specify the size of the array in the definition, it works:

struct A
{
    array<string, 2> const value;
    A (array<string, 2>&& v): value {v} {}
};

A a { { "hello", "there" } };

Is it possible to write a deduction guide for this case? If so, how?
If not, how else could I solve this problem?

Upvotes: 2

Views: 192

Answers (1)

Sam Varshavchik
Sam Varshavchik

Reputation: 118435

This works for me on gcc 11 with -std=c++17:

#include <string>
#include <array>

using namespace std;

template <size_t N>
struct A
{
    array<string, N> const value;
    A (array<string, N>&& v): value {v} {}
};

template<typename T, size_t N>
A( T (&&) [N]) -> A<N>;

A a { { "hello", "there" } };

Live example

Upvotes: 3

Related Questions