与 std::is_constructible 和 if constexpr

问题描述

如果我举个例子可能最容易解释:

#include <iostream>
#include <type_traits>

class Unconstructible
{
public:
    Unconstructible() = delete;
};


int main()
{
    if constexpr (std::is_constructible_v<Unconstructible>)
    {
        std::cout << "Unconstructible is constructible. What?\n";
        // Unconstructible foo;
    }
    else
    {
        std::cout << "Unconstructible is not constructible.\n";
    }

    return 0;
}

这会按预期输出“不可构造的不可构造的”。但是,如果我取消注释 Unconstructible foo; 行,则会出现编译错误

1>F:\Programming\C++\CppScratchwork\CppScratchwork\CppScratchwork\CppScratchwork.cpp(48): error C2280: 'Unconstructible::Unconstructible(void)': attempting to reference a deleted function
1>F:\Programming\C++\CppScratchwork\CppScratchwork\CppScratchwork\CppScratchwork.cpp(39): message : see declaration of 'Unconstructible::Unconstructible'
1>F:\Programming\C++\CppScratchwork\CppScratchwork\CppScratchwork\CppScratchwork.cpp(39,5): message : 'Unconstructible::Unconstructible(void)': function was explicitly deleted
1>Done building project "CppScratchwork.vcxproj" -- Failed.

这是在 MSVC 中使用 /std:c++17。使用 -std=c++17 在 GCC 上显示相同的行为,但带有不同措辞的错误消息,涉及尝试引用已删除函数

为什么它甚至试图编译 if constexpr 分支的第一部分?据我所知,它能够正确地判断 std::is_constructible_v<Unconstructible>false

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)