簡體   English   中英

獲取指向模板化 lambda 運算符 () 的指針,無需捕獲

[英]Get a pointer to a templated lambda operator () without captures

誰能告訴我一種有效的方法來獲取指向模板化的 lamda(無頭)運算符 () 的指針? 已經嘗試了兩種選擇:

int main()
{
    static
    auto l = []<bool a, bool b>( unsigned c ) -> unsigned
    {
        return (unsigned)a + b + c;
    };
    using fn_t = unsigned (*)( unsigned );
    fn_t fnA = &l.operator ()<true, false>; // doesn't work
    fn_t fnB = &decltype(l)::operator ()<true, false>; // also doesn't work
}

鏗鏘聲(-cl)12:

x.cpp(9,13): error: cannot create a non-constant pointer to member function
        fn_t fnA = &l.operator ()<true, false> ; // doesn't work
                   ^~~~~~~~~~~~~~~~~~~~~~~~~~~
x.cpp(10,14): error: address of overloaded function 'operator()' does not match required type
      'unsigned int (unsigned int)'
        fn_t fnB = &decltype(l)::operator ()<true, false> ; // also doesn't work
                    ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
x.cpp(4,11): note: candidate function template has different qualifiers (expected unqualified but found 'const')
        auto l = []<bool a, bool b>(unsigned c) -> unsigned
                 ^

MSVC 2019 最新更新:

x.cpp(9): error C2276: '&': illegal operation on bound member function expression
x.cpp(10): error C2440: 'initializing': cannot convert from 'overloaded-function' to 'fn_t'
x.cpp(10): note: None of the functions with this name in scope match the target type

lambda 的operator()的地址類型是成員 function 指針,但是,您的fn_t的定義只是一個空閑的 function 指針。 您應該將fn_t定義為:

using fn_t = unsigned int (decltype(l)::*)(unsigned int) const;

然后以下應該工作:

fn_t fnA = &decltype(l)::operator ()<true, false>;

或者,為什么不呢?

auto fnB = &decltype(l)::operator ()<true, false>;

演示。

它是 lambda 在某些情況下(此處不存在)可以轉換為 function 指針,而不是其成員operator() 並且您不能將成員指針轉換為 function 指針。

一種解決方法是使用另一個 lambda。

fn_t fn = [](unsigned c) { return decltype(l){}.operator()<true, false>(c); };

演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM