NeomerArcana
NeomerArcana

Reputation: 2301

How to avoid needing to supply template twice in constructor of class?

I have the following two classes:

template<std::size_t Num>
class Foo
{
public:
    Foo(const std::array<int,Num>& nums)
    :
        m_nums(nums){}

protected:
    const std::array<int,Num>& m_nums;
};

template<typename... Foos>
class Bar
{
public:

    Bar(Foos... foos)
    :
        m_foos(std::make_tuple(foos...))
    {

    }

protected:
    std::tuple<Foos...> m_foos;
};

That I would use like this:

int main()
{
    std::array<int,2> nums1 = {0,1};
    std::array<int,1> nums2 = {0};

    Bar<Foo<2>,Foo<1>> bar(Foo<2>(nums1), Foo<1>(nums2));

    return 0;
}

How can I avoid the need to specify Foo<2> and Foo<1> twice? I tried Bar<> bar(Foo<2>(nums1), Foo<1>(nums2)); but that didn't compile.

Upvotes: 0

Views: 58

Answers (2)

Max Langhof
Max Langhof

Reputation: 23701

With CTAD, the implicit deduction guides already have you covered:

Bar bar{Foo<2>(nums1), Foo<1>(nums2)};

https://godbolt.org/z/6g1fkf

(Note that you run into the most vexing parse here if you use parentheses instead of curly braces.)

Upvotes: 3

Maxim Egorushkin
Maxim Egorushkin

Reputation: 136425

The constructor can just forward the arguments:

Bar(Foos... foos)
    : m_foos(std::move(foos)...)
{}

And then:

Bar<Foo<2>,Foo<1>> bar(nums1, nums2);

Upvotes: 1

Related Questions