c++ - 如果在 lambda 中,MSVC 不尊重 constexpr

标签 c++ gcc visual-c++ lambda

我所指的例子:

#include <type_traits>

void voidFunction() {}

template <typename Function>
void lambdaTest(Function func) {
    [func]() -> void {
        int someInt;
        if constexpr (std::is_same_v<std::invoke_result_t<Function>, int>) {
            someInt = std::invoke(func);
        } else {
            std::invoke(func);
        }
    };
}

int main(int argc, char** argv) {
    lambdaTest(&voidFunction);
    return 0;
}

这在 gcc 7.2 中编译。但是,使用 MSVC 19.11.25547 时出现此错误:
错误 C2440:“=”:无法从“void”转换为“int”

这段代码在两个编译器上都能正常编译:

#include <type_traits>

void voidFunction() {}

template <typename Function>
void nonLambdaTest(Function func) {
    int someInt;
    if constexpr (std::is_same_v<std::invoke_result_t<Function>, int>) {
        someInt = std::invoke(func);
    } else {
        std::invoke(func);
    }
}

int main(int argc, char** argv) {
    nonLambdaTest(&voidFunction);
    return 0;
}

在我看来,MSVC 只是忽略了 constexpr if。这是 MSVC 中的错误,还是 constexpr(如果在 lambda 中被正式禁止)?

最佳答案

我稍微简化了这个例子(或者至少让它更明显):

#include <type_traits>
#include <utility>

template<typename TPointerToFunction>
void lambdaTest(TPointerToFunction)
{
    []() -> void // comment this line to make it work
    {
        constexpr const bool returns_int
        {
            std::is_same_v
            <
                int
            ,   decltype(::std::declval<TPointerToFunction>()())
            >
        };
        static_assert(!returns_int);
        if constexpr(returns_int)
        {
            static_assert(returns_int, "how did we get here?");
        }
    };
}

void voidFunction(void) {}

int
main()
{
    lambdaTest(&voidFunction);
    return(0);
}

关于c++ - 如果在 lambda 中,MSVC 不尊重 constexpr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47269793/

相关文章:

c++ - std::stoi 的基本参数

c++ - 在 C++ 中读取大的 txt 文件

c - 这个 gcc 命令是什么意思?

c++ - 如何使用gsoap在客户端无冲突地调用多个服务

c - 如何在 GCC 上移植 __declspec(noalias)

c++ - `sizeof` C++ 应用程序中的所有类型

c++ - 如何在WSL上获取VS Code来调试C++代码?

从 backtrace_symbols 接收到的 c++ 符号不显示 g++ 中的函数

C++ eigen3 线性代数库,奇怪的性能结果

c++ - 如何在 std::map 或 std::unordered_map 之间切换作为类中的容器?