8

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.

Barry
  • 286,269
  • 29
  • 621
  • 977
Zejj
  • 83
  • 5
  • 5
    Compiler bug. Couldn't find a dupe, filed [85883](https://gcc.gnu.org/bugzilla/show_bug.cgi?id=85883). – Barry May 23 '18 at 00:28

1 Answers1

4

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};
P.W
  • 26,289
  • 6
  • 39
  • 76