c++language-lawyerdeduction-guide

Deduction guide works in gcc and msvc but rejected by clang


I am learning about deduction guides in C++. Then I wrote the following code that compiles with gcc and msvc but rejected by clang. Demo

I want to know which compiler is right here.

#include <vector>
#include <array>
#include <memory>

struct Coord
{    
    int x, y;
};

template<int N, int D = 0 >
class CoordArray
{ 
public:
    CoordArray(const Coord(&ref)[N]) 
    {}
};
template<int D, int N> CoordArray() -> CoordArray<N, D>;
CoordArray<3> myCoordArray{{{2, 1}, {4, 1}, {6, 1}}}; //clang rejects but gcc and msvc accepts
CoordArray myCoordArray2{{{2, 1}, {4, 1}, {6, 1}}};   //clang rejects but gcc and msvc accepts

Clang says:

<source>:17:24: error: deduction guide template contains template parameters that cannot be deduced
   17 | template<int D, int N> CoordArray() -> CoordArray<N, D>;
      |                        ^
<source>:17:14: note: non-deducible template parameter 'D'
   17 | template<int D, int N> CoordArray() -> CoordArray<N, D>;
      |              ^
<source>:17:21: note: non-deducible template parameter 'N'
   17 | template<int D, int N> CoordArray() -> CoordArray<N, D>;
      |

Solution

  • The program is ill-formed no diagnostic required since you're not using the ill-formed deduction guide. So technically, the compilers are not required to give a diagnostic.

    From temp#res.general:

    The program is ill-formed, no diagnostic required, if:

    • a hypothetical instantiation of a templated entity immediately following its definition would be ill-formed due to a construct (other than a static_assert-declaration that fails) that does not depend on a template parameter, or