【问题标题】:Special rules regarding SFINAE for incomplete types关于不完整类型的 SFINAE 的特殊规则
【发布时间】:2017-11-04 12:44:34
【问题描述】:

最近在if-else depends on whether T is a complete type这里回答一个问题时,我意识到以下内容无法编译

#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 启动并使类的默认定义成为实例化的类吗?

【问题讨论】:

    标签: c++ templates template-specialization incomplete-type


    【解决方案1】:

    尝试实例化DetermineCompleteHelper&lt;IncompleteType&gt; 的定义时发生错误(特别是,它尝试从不完整的基类派生)。这超出了直接上下文。

    【讨论】:

    • sizeof(DetemineCompleteHelper&lt;IncompleteType&gt;) 在直接上下文中的情况如何?那也不会尝试查看实例化后的类的大小吗?
    • @Curious 您的“编译”示例是sizeof(IncompleteType)
    • ...nvm,我问得太早了,好像应该在问之前阅读我写的代码
    猜你喜欢
    • 2013-05-19
    • 1970-01-01
    • 1970-01-01
    • 2017-04-10
    • 2018-01-13
    • 1970-01-01
    • 2020-11-13
    • 2013-01-11
    • 1970-01-01
    相关资源
    最近更新 更多