我想通過一個非捕獲lambda,返回一個 std::unique_ptr<Derived>
,作爲類型爲std::unique_ptr<Base>(*)()
的函數指針。將返回多態unique_ptr的lambda作爲函數指針傳遞
但是,如果我明確規定的拉姆達的返回類型std::unique_ptr<Base>
這僅適用。
- 爲什麼我明確指出返回類型?
- 爲什麼它的
std::function
工作,而這些額外的返回類型?
#include <functional>
#include <memory>
struct Base{virtual ~Base()=default;};
struct Derived : Base{};
struct FailsForF2
{
using Function = std::add_pointer_t<std::unique_ptr<Base>()>;
FailsForF2(Function f) {}
};
struct Works
{
using Function = std::function<std::unique_ptr<Base>()>;
Works(Function f) {}
};
std::unique_ptr<Derived> fun() {return std::make_unique<Derived>();}
int main()
{
auto f1 = [](){return std::make_unique<Base>();};
auto f2 = [](){return std::make_unique<Derived>();};
auto f3 = []()->std::unique_ptr<Base>{return std::make_unique<Derived>();};
Works x1(f1);
Works x2(f2);
Works x3(f3);
FailsForF2 x4(f1);
FailsForF2 x5(f2);
FailsForF2 x6(f3);
}
GCC錯誤:
main.cpp: In function 'int main()':
main.cpp:34:20: error: invalid user-defined conversion from 'main()::<lambda()>' to 'FailsForF2::Function {aka std::unique_ptr<Base> (*)()}' [-fpermissive]
FailsForF2 x5(f2);
^
main.cpp:26:17: note: candidate is: main()::<lambda()>::operator std::_MakeUniq<Derived>::__single_object (*)()() const <near match>
auto f2 = [](){return std::make_unique<Derived>();};
^
main.cpp:26:17: note: no known conversion from 'std::_MakeUniq<Derived>::__single_object (*)() {aka std::unique_ptr<Derived> (*)()}' to 'FailsForF2::Function {aka std::unique_ptr<Base> (*)()}'
main.cpp:10:4: note: initializing argument 1 of 'FailsForF2::FailsForF2(FailsForF2::Function)'
FailsForF2(Function f) {}
不會'std :: add_pointer_t>;'是指向'unique_ptr '的指針嗎?請參閱http://coliru.stacked-crooked.com/a/5a1c461bfb6199a8 我可能不是專家,但我可以猜測編譯器在轉換時將'unique_ptr '轉換爲指向'unique_ptr '的指針時出現問題一個'unique_ptr '指向'unique_ptr '它可以以某種方式隱式地執行 –
Hayt
@Hayt我使用'std :: add_pointer_t()>;'請注意'()'在末尾 –
啊,對啊。那麼不要那麼着急。它可能必須做一些功能ptr(第一個)的不同行爲和一些轉換的函數對象,但我現在找不到任何的鏈接(與lambda一起組合)。可能會有一些轉換一個lambda到一個c函數ptr也)。 – Hayt