Conjuction template doesn't short circuit

家住魔仙堡 提交于 2019-12-23 16:40:06

问题


I want to be able to evaluate whether a function accepts one argument of type int, and whether it returns void. To that end I used std::conjunction since I believed it was supposed to short-circuit and not evaluate the second ill-formed expression in case the function is not callable with one argument of type int, but for some reason I get a compiler error:

#include <iostream>
#include <type_traits>
template<typename Function>
struct oneArgVoid
{
    static constexpr bool value = std::conjunction_v<std::is_invocable<Function, int>, std::is_void<std::invoke_result_t<Function, int>>>;
};

int main()
{
    auto l1 = [](auto x) {};
    std::cout << oneArgVoid<decltype(l1)>::value << "\n";
    auto l2 = [](auto x) {return 1; };
    std::cout << oneArgVoid<decltype(l2)>::value << "\n";
    auto l3 = [](auto x, auto y) {};
    std::cout << oneArgVoid<decltype(l3)>::value << "\n";
    return 0;
}

Note that if oneArgVoid is not called on l3 the code compiles. Live demo: https://godbolt.org/z/8BUfpT

I do not use boost, so I cannot use mpl::eval_if. But I thought that std::conjunction was supposed to short circuit here, am I wrong?

Considering HolyBlackCat's suggestion, here's something even stranger: https://godbolt.org/z/2SUij-


回答1:


It seems like std::conjunction short-circuits only on the values of the types, the types themselves still have to be well-formed. So this: std::is_void<std::invoke_result_t<Function, int>> is actually rightfully illegal here. Due to that with the modification:

template<typename Function>
struct argVoid
{
    static constexpr bool value = std::is_void_v<std::invoke_result_t<Function, int>>;
};

template<typename Function>
struct oneArgVoid
{
    static constexpr bool value = std::conjunction_v<std::is_invocable<Function, int>, argVoid<Function>>;
};

It works, since the ill-formed expression is now in the value variable, which means it doesn't get evaluated due to the short-circuit.



来源:https://stackoverflow.com/questions/57018826/conjuction-template-doesnt-short-circuit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!