首页 > 解决方案 > 调用模板化 lambda (C++20) 的模板 lambda 不适用于 clang 12 / 13

问题描述

考虑这段代码:

#include <utility>
#include <functional>

using namespace std;

int main( int argc, char **argv )
{
    static
    auto lA = []<bool FLAG_A, bool FLAG_B>( unsigned a ) -> unsigned
    {
        return (unsigned)FLAG_A + FLAG_B + a;
    };
    static
    auto lB = []<bool FLAG_A, bool FLAG_B>( unsigned a ) -> unsigned
    {
        return lA.template operator ()<FLAG_A, FLAG_B>( a );
    };
    using fn_t = function<unsigned ( unsigned )>;
    fn_t fn = bind( &decltype(lB)::template operator ()<false, false>, &lB, placeholders::_1 );
}

这与 MSVC 2019 编译没有任何问题,但 clang 12 / 13 给出以下错误:

test.cpp(11,12): error: multiple overloads of '__invoke' instantiate to the same signature 'auto (unsigned int) const -> unsigned int'
        auto lA = []<bool FLAG_A, bool FLAG_B>( unsigned a ) -> unsigned
                  ^
test.cpp(11,12): note: in instantiation of member class '' requested here
test.cpp(21,42): note: in instantiation of function template specialization 'main(int, char **)::(anonymous class)::operator()<false, false>' requested here
        fn_t fn = bind( &decltype(lB)::template operator ()<false, false>, &lB, placeholders::_1 );
                                                ^
test.cpp(11,12): note: previous implicit declaration is here
        auto lA = []<bool FLAG_A, bool FLAG_B>( unsigned a ) -> unsigned
                  ^

gcc 11 也编译代码没有任何错误。有没有办法使代码也可以在没有任何复杂的解决方法的情况下与 clang 一起使用?

标签: c++c++20

解决方案


仍然std::integral_constant(甚至 std::bool_constant在您的情况下)允许扣除:

static auto lA = []<bool FLAG_A, bool FLAG_B>(std::bool_constant<FLAG_A>,
                                              std::bool_constant<FLAG_B>,
                                              unsigned a ) -> unsigned
{
    return (unsigned)FLAG_A + FLAG_B + a;
};
static
auto lB = []<bool FLAG_A, bool FLAG_B>( unsigned a ) -> unsigned
{
    return lA(std::bool_constant<FLAG_A>{}, std::bool_constant<FLAG_B>{}, a);
};

演示


推荐阅读