【问题标题】:Why specialization and template does not match?为什么专业化和模板不匹配?
【发布时间】:2020-08-07 06:03:43
【问题描述】:

我是 C++ 模板的新手。 这是我为测试std::enable_if_t 员工而编写的示例代码。 但它没有编译并出现以下错误:

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

我做错了什么?

#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);
   }
}

【问题讨论】:

    标签: c++ c++11 templates sfinae template-specialization


    【解决方案1】:

    首先,您将SFINAEfunction specialization 混合在一起。它不会那样工作。你需要选择一个。

    其次,启用 if 始终为true,这样无论T 是什么,它都会一直被选中。

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

    您需要以下内容()才能使 SFINAE 工作:

    #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);
       }
    }
    

    附带说明,在 中,这将使用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;
       }
    }
    

    【讨论】:

    • @Daa,在编译器选择主模板后,它会考虑特化。你为一些T 专门化了一个函数模板,但是T 在那个专门化中是什么?没有明确提供,也无法推导出来。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多