简体   繁体   中英

Why specialization and template does not match?

I am quite new in c++ templates. This is the sample code I have written to test std::enable_if_t staff. But it does not compile with following error:

No function template matches function template specialization 'print'
Candidate template ignored: couldn't infer template argument 'T'

What am I doing wrong?

#include <string>
#include <type_traits>

class IPoint
{
public:
   IPoint()
      : x(0), y(0)
   {}

   IPoint(int xValue, int yValue)
      : x(xValue), y(yValue)
   {}

public:
   int x;
   int y;
};

namespace utils
{
   template<typename T>
   typename std::enable_if_t<true, T> print(const std::string& s) 
   {
      return 0;
   }

   template<>
   inline IPoint print(const std::string& s)
   {
      return IPoint(0, 0);
   }
}

First of all, you are mixing SFINAE with function specialization . It will not work like that. You need to pick one.

Secondly, enable if is always true , so it will be always selected, no matter what the T is.

std::enable_if_t<true, T>
//               ^^^^

You need the following (in ) for the SFINAE to work:

#include <type_traits> // std::is_same

namespace utils
{
   template<typename T>
   typename std::enable_if<!std::is_same<IPoint, T>::value, T>::type // T != IPoint 
      print(const std::string& s)
   {
      return 0;
   }

   template<typename T>
   typename std::enable_if<std::is_same<IPoint, T>::value, T>::type   // T == IPoint 
      print(const std::string& s)
   {
      return IPoint(0, 0);
   }
}

As a side note, in , this will be reduced to one single template function using if constexpr

namespace utils
{
   template<typename T>
   auto print(const std::string& s) 
   {
      if constexpr (std::is_same<IPoint, T>::value)
         return IPoint(0, 0);
      else
         return 0;
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM