Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template argument deduction failure with new expression

I'm working on a variadic class template but I cannot use it with a new expression without specifying the template arguments (I don't want to). I reduced the problem to the following code sample:

template <typename T>
struct Foo
{
    Foo(T p)
        : m(p)
    {}

    T m;
};

template <typename T1, typename T2>
struct Bar
{
    Bar(T1 p1, T2 p2)
        : m1(p1), m2(p2)
    {}

    T1 m1;
    T2 m2;
};

int main()
{
    double p = 0.;

    auto stackFoo = Foo(p);       // OK
    auto heapFoo = new Foo(p);    // OK

    auto stackBar = Bar(p, p);    // OK
    auto heapBar = new Bar(p, p); // error: class template argument deduction failed

    return 0;
}

From what I understand from cppreference the compiler should be able to deduce the template arguments in every cases above. I can't figure out why there is no error with heapFoo too.

So am I missing something here?

I'm using gcc 7.2.0 on Xubuntu 17.10 with -std=c++17 flag.

like image 822
Zejj Avatar asked May 22 '18 23:05

Zejj


Video Answer


1 Answers

The bug 85883 titled: "class template argument deduction fails in new-expression" filed by Barry has been fixed for GCC 9.

The error does not appear in GCC Trunk (DEMO).

As a workaround for GCC 7.2, you can use value initialization form like below. (DEMO):

auto heapBar = new Bar{p, p};
like image 173
P.W Avatar answered Oct 21 '22 19:10

P.W