2017-06-03 73 views
0

近日在回答一个问题在这里if-else depends on whether T is a complete type我意识到,下面无法编译关于SFINAE为不完全类型

#include <iostream> 
#include <type_traits> 

using namespace std; 

class Incomplete; 
class Complete {}; 

template <typename IncompleteType> 
struct DetermineCompleteHelper : public IncompleteType {}; 

template <typename IncompleteType, typename = std::enable_if_t<true>> 
struct DetermineComplete { 
    static constexpr const bool value = false; 
}; 

template <typename IncompleteType> 
struct DetermineComplete<IncompleteType, std::enable_if_t<std::is_same< 
     decltype(DetermineCompleteHelper<IncompleteType>{}), 
     decltype(DetermineCompleteHelper<IncompleteType>{})>::value>> { 
    static constexpr const bool value = true; 
}; 

int main() { 
    cout << DetermineComplete<Complete>::value << endl; 
    cout << DetermineComplete<Incomplete>::value << endl; 
    return 0; 
} 

但改变局部模板专业化

template <typename IncompleteType> 
struct DetermineComplete<IncompleteType, std::enable_if_t<std::is_same< 
     std::integer_sequence<int, sizeof(IncompleteType)>, 
     std::integer_sequence<int, sizeof(IncompleteType)>>::value>> { 
    static constexpr const bool value = true; 
}; 

特殊规则使代码编译没有错误,为什么这种不规范?不应该将第一个表达式视为部分特化的上下文中的错误,并因此让SFINAE启动并使该类的默认定义成为实例化的类型?

回答

3

尝试实例化DetermineCompleteHelper<IncompleteType>(特别是,它试图从不完整的基类派生)的定义时发生该错误。这不在眼前的情况下。

+0

在直接上下文中,sizeof(DetemineCompleteHelper )如何?这样做是否也会尝试查看实例化类的大小? – Curious

+0

@Curious你的“编译”例子是'sizeof(IncompleteType)'。 –

+0

... nvm,我问得太快了,应该先阅读我之前写的代码 – Curious