【问题标题】:How to specialize a template function for enum, and specific type?如何为枚举和特定类型专门化模板函数?
【发布时间】:2015-04-21 04:26:11
【问题描述】:

我目前有一个函数:

template<typename T> 
bool func(T &t, int x)
{
    // do stuff...
}

但是我想要三个不同的函数体:

  1. Tenum
  2. Tunsigned char
  3. 其他一切

我已经尝试过this,但没有成功。

这三种情况下正确的函数声明是什么?


我能想到的最接近的是案例 1:

template<typename T>
typename std::enable_if< std::is_enum<T>::value, bool >::type func( T &t, int x)

情况 3 是:

template<typename T>
typename std::enable_if< not std::is_enum<T>::value, bool >::type func( T &t, int x)

但是,我无法为可编译的案例 2 做一些事情。作为一种解决方法,我在案例 3 中有一个 if 语句来处理无符号字符,但这并不理想。

【问题讨论】:

  • “但是我无法为案例 2 编译” bool func( unsigned char t, int x ) 的简单重载怎么样?
  • 为什么所有枚举都应该与所有其他类型区别对待?枚举没有一组将它们与其他类型区分开来的常见行为。或者这只是一个学术练习?
  • @PiotrS。我最初这样做时遇到了多重定义错误,但直到现在才意识到可以通过将其设置为 inline bool func ( unsigned char t, int x ); 来解决此问题
  • @Brian Case 3 of func 使用 istream::operator&gt;&gt;t,这不是为枚举定义的。 (我想为枚举做一些完全不同的事情,不能通过重载运算符来解决>>)。

标签: c++ templates c++11 sfinae


【解决方案1】:

使用标签调度:

namespace details {
  template<class T>
  bool func( T& t, int x, std::true_type /* is_enum */, std::false_type ) {
  }
  template<class T>
  bool func( T& t, int x, std::false_type, std::true_type /* unsigned char */ ) {
  }
  template<class T>
  bool func( T& t, int x, std::false_type, std::false_type ) {
    // neither
  }
}
template<class T>
bool func( T& t, int x ) {
  return details::func( t, x, std::is_enum<T>{}, std::is_same<unsigned char, T>{} );
}

【讨论】:

  • 这可能比乱搞 enable_if 干净得多
  • 你不能也用std::is_unsigned&lt;T&gt;{}吗?
  • @0x49 为什么会有帮助?我有 3 个案例要处理,无法可靠地区分它们。
【解决方案2】:

把关于超载的评论变成答案:

// For enum
template<typename T>
typename std::enable_if<std::is_enum<T>::value, bool>::type
func(T& t, int x);

// for unsigned char
bool func(unsigned char& t, int x);

// for other
template<typename T>
typename std::enable_if<!std::is_enum<T>::value, bool>::type
func(T& t, int x);

Live example

另一种方法是对unsigned char 使用特化:

// for other
template<typename T>
typename std::enable_if<!std::is_enum<T>::value, bool>::type
func(T& t, int x);

// specialization for unsigned char
template <>
bool func(unsigned char& t, int x);

Live example

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-25
    • 1970-01-01
    • 2014-10-01
    • 1970-01-01
    • 2014-03-25
    相关资源
    最近更新 更多