c++ 模板特化与 std::enable_if 不工作

标签 c++ templates template-specialization partial-specialization

我有一个简单的主函数模板,我想对其进行部分特化。

template< typename T >
void SetAttribute( const T& value )
{
  static_assert( false, "SetAttribute: wrong type!" );
}

template<> void SetAttribute( const bool& value ) {}

template<> void SetAttribute( const std::wstring& value ) {}

template< typename T >
void SetAttribute( const typename std::enable_if< std::is_integral< T >::value >::type& value ) {}

int main()
{
  SetAttribute( std::wstring( L"bla" ) );
  SetAttribute( bool( true ) );
  SetAttribute( std::uint32_t( 1 ) ); // error C2338: SetAttribute: wrong type!

  return 0;
}

当我使用 VS 2015 Update 3 编译它时,我会在 3d 调用中遇到错误(请参阅评论)。为什么?我不明白为什么不使用 3d 特化。

谢谢 弗雷德

最佳答案

问题是您在 non-deduced context 中使用 T

template< typename T >
void SetAttribute( const typename std::enable_if< std::is_integral< T >::value >::type& value ) {}
                                                                    ^

函数可能不是这项工作的错误工具(它们不能部分特化),如果您坚持使用函数,可能的解决方法可能是标签分派(dispatch)和特化的组合

template<class T>
void SetAttribute(const T&, std::true_type) {}

template<class T>
void SetAttribute(const T& value, std::false_type)
{
  static_assert(std::is_integral<T>::value, "SetAttribute: wrong type!");
}

template< typename T >
void SetAttribute(const T& value)
{
  SetAttribute(value, std::is_integral<T>());
}

template<> void SetAttribute(const bool&) {}

template<> void SetAttribute(const std::wstring&) {}

Example

如果你问我的话,完全不可读..

关于c++ 模板特化与 std::enable_if 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41012809/

相关文章:

c++ - C++ 中的编译流程

c++ - 无法删除我的临时指针?

c++ - C++模板特化和函数返回值

c++ - 如何在 C++ 模板类中为单个方法创建专门化?

c++ - 删除基类指针时 'delete' 是如何工作的

c++ - 调用 system() 的行为与在命令提示符 (cmd) 中的行为不同

C++模板回调去抖动函数

c++ - 使用 C++ 模板或宏来生成编译时函数

c++ - 使用特征参数进行模板推导

c++ - 如何选择部分模板特化?