Search code examples
c++templateslanguage-lawyerc++17template-argument-deduction

Can one use function style-cast expressions involving deduction of class template argument(s) freely?


Consider an example:

template <class T>
struct tag { 
    tag(T) {}
};

int main() {
              tag(int{});     //#1
    auto t1 = tag(int{});     //#2
    auto t3 = (tag(int{}));   //#3
}

tag has an automatic deduction guides which should be involved in deduction of the class template argument. At least I thought it should as #1 and #3 act a bit unexpectedly in [clang]. On the other hand everything compiles fine in [gcc]. So the question is can I freely use deduction of class template argument in function style-cast expressions or are there any restrictions in the matter?

The error list of clang:

prog.cc:7:19: error: expected unqualified-id
              tag(int{});     //#1
                  ^
prog.cc:7:19: error: expected ')'
prog.cc:7:18: note: to match this '('
              tag(int{});     //#1
                 ^
prog.cc:9:23: error: expected ')'
    auto t3 = (tag(int{}));   //#3
                      ^
prog.cc:9:19: note: to match this '('
    auto t3 = (tag(int{}));   //#3
                  ^
prog.cc:9:27: error: expected expression
    auto t3 = (tag(int{}));   //#3
                          ^
4 errors generated.

Solution

  • This is a known bug, #34091. Basically, clang doesn't expect to get a template-id there. It'll get fixed eventually (but not in 5.0.1 I'm afraid).

    To answer your question, yes, gcc is completely right. I would really be angry at the standards committee if class template argument deduction wouldn't work for those two simple cases. :P