是否可以獲得指向通用 lambda 的特定實體化的(成員)函式指標?
我知道我可以為標準的非捕獲 lambda 和縮寫模板這樣做,但我似乎無法為通用的發明型別的顯式實體化 operator() 呼叫操作員成員函式獲取成員函式指標拉姆達。
#include <iostream>
void f1( auto v) { std::cout << v << std::endl; }
int main() {
void (*pf)(int) = f1<int>; // OK
void (*pf2)(int) = [](int v) { std::cout << v << std::endl; } ; // OK
[](auto v) { std::cout << v << std::endl; }.operator() < int > (42); // OK
auto generic_template = [](auto v) { std::cout << v << std::endl; } ;
using generic_type = decltype (generic_template);
// void (generic_type::*pf3)(int) = &generic_type::operator()<int>; // fails to compile
pf(5);
}
這里的興趣是學術性的。
編輯:
作為未來讀者感興趣的注釋,除了通用 lambda 之外,為這個問題提供的解決方案也適用于獲取具有捕獲的 lambda 的函式指標。例如,根據答案:
auto generic_lambda = [](auto v) { std::cout << v << std::endl; } ;
using generic_type = decltype (generic_lambda);
void (generic_type::*pf1)(int) const = &generic_type::operator();
(&generic_lambda->*pf1)(43); // OK
int x = 5;
auto capturing_lambda = [x](int v) { std::cout << v x << std::endl; } ;
using capturing_type = decltype (capturing_lambda);
void (capturing_type::*pf2)(int) const = &capturing_type::operator();
(&capturing_lambda->*pf2)(43); // OK
uj5u.com熱心網友回復:
是的,如果模板引數可以從被初始化的型別(或強制轉換的結果型別)推匯出來,則可以省略模板引數,但由于 lambda 不是mutable成員函式const,因此必須是指向成員的指標。
uj5u.com熱心網友回復:
是否可以獲得指向通用 lambda 的特定實體化的(成員)函式指標?
Lambda的默認operator()是const-qualified,需要添加const到成員函式指標型別
void (generic_type::*pf3)(int) const = &generic_type::operator();
并且由于pf3是一個成員函式指標,請注意它需要一個特定的lambda 物件并使用.*or->*來呼叫。
(generic_template.*pf3)(42);
演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/410786.html
標籤:
下一篇:std::thread::hardware_concurrency()未在AMDRyzenthreadripper3990x中回傳正確數量的邏輯處理器
