13

C++17 introduces template argument deduction.

With gcc-7.2, I can use it easily in a function:

int test() {
  std::pair d(0, 0.0);
}

I was expecting this same syntax to work in class non-static data members, like:

class Test {
  std::pair d_{0, 0.0};
};

but this causes gcc error: invalid use of template-name ... without an argument list, with --std=c++17 passed.

I tried a few other combinations, but none seems to work.

Is this the intended behavior by the standard, or is this a case of incomplete support by the compiler? I can't find any explicit reference to class data members in the standard.

My use case is of course much more complex, having this syntax would be extremely convenient (think functions being passed and stored).

3
  • I'm not sure about what exactly you are asking. The standard can require behavior, and the committee can intend behavior. Do you mean: 1) behavior required by the Standard, or do you mean 2) behavior intended by the C++ committee? Nov 21, 2017 at 17:43
  • 1
    @JohannesSchaub-litb The question is fairly clearing asking if it's the correct behavior per the standard or a compiler bug.
    – Barry
    Nov 21, 2017 at 18:41
  • Possible workaround: decltype(std::pair{0, 0.0}) d_{0, 0.0};
    – W.F.
    Nov 21, 2017 at 18:49

1 Answer 1

10

Is this the intended behavior by the standard, or is this a case of incomplete support by the compiler?

Yes, this is intended behavior. [dcl.type.class.deduct] reads:

If a placeholder for a deduced class type appears as a decl-specifier in the decl-specifier-seq of an initializing declaration ([dcl.init]) of a variable, [...]

A placeholder for a deduced class type can also be used in the type-specifier-seq in the new-type-id or type-id of a new-expression, or as the simple-type-specifier in an explicit type conversion (functional notation). A placeholder for a deduced class type shall not appear in any other context.

A non-static data member is not a variable, and we're in none of the other situations.

Note that the same principle is true for non-static data members attempting to be declared with auto:

struct X {
    auto y = 0; // error
};

The default member initializer is just that - a default initializer. What if you provided a constructor that initialized the member with expression(s) of different types?

1
  • As for the intended behavior of the committee, the paper proposal said "Simple declarations of variables (or variable templates) that are also definitions whose declarator is a noptr-declarator (i.e. not when declaring functions, template parameters, function parameters, non-static data members, pointers, references etc.)". Nov 21, 2017 at 17:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.