std :: enable_if:参数与模板参数 [英] std::enable_if : parameter vs template parameter

查看:356
本文介绍了std :: enable_if:参数与模板参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm building some input checker that needs to have specific functions for integer and/or double (for example 'isPrime' should only be available for integers).

如果我使用 enable_if 作为参数,它可以正常工作:

If I'm using enable_if as a parameter it's working perfectly :

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 )

but if I'm using it as a template paramater (as demonstrated on 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()’

我不知道第二个错误是什么版本。

I can't figure out what is wrong in the second version.

推荐答案

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

Default template arguments are not part of the signature of a template (so both definitions try to define the same template twice). Their parameter types are part of the signature, however. So you can do

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

这篇关于std :: enable_if:参数与模板参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆