繁体   English   中英

std::enable_if :参数与模板参数

[英]std::enable_if : parameter vs template parameter

我正在构建一些输入检查器,它需要具有整数和/或双精度的特定函数(例如,'isPrime' 应该只适用于整数)。

如果我使用enable_if作为参数,它运行良好:

template <class T>
class check
{
public:
   template< class U = T>
   inline static U readVal(typename std::enable_if<std::is_same<U, int>::value >::type* = 0)
   {
      return BuffCheck.getInt();
   }

   template< class U = T>
   inline static U readVal(typename std::enable_if<std::is_same<U, double>::value >::type* = 0)
   {
      return BuffCheck.getDouble();
   }   
};

但如果我将它用作模板参数(如http://en.cppreference.com/w/cpp/types/enable_if 所示

template <class T>
class check
{
public:
   template< class U = T, class = typename std::enable_if<std::is_same<U, int>::value>::type >
   inline static U readVal()
   {
      return BuffCheck.getInt();
   }

   template< class U = T, class = typename std::enable_if<std::is_same<U, double>::value>::type >
   inline static U readVal()
   {
      return BuffCheck.getDouble();
   }
};

然后我有以下错误:

error: ‘template<class T> template<class U, class> static U check::readVal()’ cannot be overloaded
error: with ‘template<class T> template<class U, class> static U check::readVal()’

我无法弄清楚第二个版本有什么问题。

默认模板参数不是模板签名的一部分(因此两个定义都尝试定义相同的模板两次)。 然而,它们的参数类型是签名的一部分。 所以你可以做

template <class T>
class check
{
public:
   template< class U = T, 
             typename std::enable_if<std::is_same<U, int>::value, int>::type = 0>
   inline static U readVal()
   {
      return BuffCheck.getInt();
   }

   template< class U = T, 
             typename std::enable_if<std::is_same<U, double>::value, int>::type = 0>
   inline static U readVal()
   {
      return BuffCheck.getDouble();
   }
};

问题是编译器看到同一个方法的 2 个重载,它们都包含相同的参数(在这种情况下没有)和相同的返回值。 你不能提供这样的定义。 最简洁的方法是在函数的返回值上使用 SFINAE:

template <class T>
class check
{
public:
   template< class U = T>
   static typename std::enable_if<std::is_same<U, int>::value, U>::type readVal()
   {
      return BuffCheck.getInt();
   }

   template< class U = T>
   static typename std::enable_if<std::is_same<U, double>::value, U>::type readVal()
   {
      return BuffCheck.getDouble();
   }
};

这样,您就提供了 2 种不同的重载。 一个返回一个int,另一个返回一个double,并且只有一个可以使用某个T来实例化。

我知道这个问题是关于std::enable_if ,但是,我喜欢提供一种替代解决方案来解决没有 enable_if 的相同问题。 它确实需要 C++17

template <class T>
class check
{
public:
   inline static T readVal()
   {
        if constexpr (std::is_same_v<T, int>)
             return BuffCheck.getInt();
        else if constexpr (std::is_same_v<T, double>)
             return BuffCheck.getDouble();
   }   
};

这段代码看起来更像是在运行时编写的。 所有分支都必须在句法上正确,但语义不必如此。 在这种情况下,如果 T 是 int,则 getDouble 不会导致编译错误(或警告),因为它不会被编译器检查/使用。

如果函数的返回类型很复杂,您可以始终使用auto作为返回类型。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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