c++c++20template-specializationdecltype

Template specialization failure while using decltype in template type


I defined the following template structure:

template<typename T>  struct somestruct {}; 

and now the following specializations:

template<typename T> struct somestruct <std::vector<T>>                {};  // OK
template<typename T> struct somestruct <decltype(std::vector<T>  {})>  {};  // KO

However, the last specialization doesn't compile with the following error (see here):

error: template parameters not deducible in partial specialization:

Naively, I would say that the two specializations are not so different, like the following seems to say:

template<typename T> void test ()  
{ 
    static_assert (std::is_same_v<std::vector<T>, decltype(std::vector<T>{})> );
}

Question: what is the technical reason that makes the compiler fail with the second specialization ? And is there a way to fix it (I mean my code, not the compiler) ?

There is an old post that seems to be similar but maybe things/compiler/c++ may have changed.


Solution

  • Because template argument deduction can't work due to non deduced context.

    If a template parameter is used only in non-deduced contexts and is not explicitly specified, template argument deduction fails.

    1. The expression of a decltype-specifier:

      template<typename T>
      void f(decltype(*std::declval<T>()) arg);
      
      int n;
      f<int*>(n); // P = decltype(*declval<T>()), A = int: T is in non-deduced context
      

    The 2nd code snippet is not exactly the same because template argument deduction isn't involved.