我有一个简单的主函数模板,我想对其进行部分特化。
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&) {}
如果你问我的话,完全不可读..
关于c++ 模板特化与 std::enable_if 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41012809/