TestCase2并且TestCase3可以正常編譯。但是,在TestCase1我收到以下錯誤:
E0312, Custom conversion from "lambda []void ()->void" to
"EventHandler" is not appropriate.
為什么我會收到此錯誤?我想知道如何解決它。
#include <functional>
#include <iostream>
class EventHandler
{
std::function<void()> _func;
public:
int id;
static int counter;
EventHandler() : id{ 0 } {}
EventHandler(const std::function<void()>& func) : _func{ func }
{
id = EventHandler::counter;
}
};
int EventHandler::counter = 0;
int main()
{
EventHandler TestCase1 = []() {};
EventHandler TestCase2([]() {});
EventHandler TestCase3 = static_cast<std::function<void()>>([]() {});
}
uj5u.com熱心網友回復:
為什么我會收到此錯誤?
lambda[]() {}與 不同std::function<void()>。這意味著
decltype([]() {}) != std::function<void()>
它必須被隱式或顯式轉換。
在線上
EventHandler TestCase1 = []() {};
復制初始化發生,編譯器首先必須將 lambda 轉換為 astd::function<void()>然后是EventHandler物件。編譯器不能做雙重隱式約定。
因此,您需要在這里明確,TestCase3例如。
我想知道如何解決它。
一種方法是提供一個模板化的建構式(如果你愿意的話)
#include <type_traits> // std::is_convertible_v
class EventHandler
{
std::function<void()> _func;
public:
template<typename Func> EventHandler(Func func)
: _func{ func }
{
static_assert(std::is_convertible_v<Func, decltype(_func)>
, "is not valid arg!");
// ....
}
// or in C 20 with <concepts> header
// template<typename Func> EventHandler(Func func)
// requires std::convertible_to<Func, decltype(_func)>
// : _func{ func }
// { ... }
};
現在你可以
EventHandler TestCase1 = []() {}; // works
演示
uj5u.com熱心網友回復:
您不能將 lambda 直接分配給EventHandler,沒有這樣的轉換。相反,您可以EventHandler通過添加花括號來呼叫 的建構式,這將std::function使用 lambda 初始化 。
EventHandler TestCase1 = {[]() {}};
uj5u.com熱心網友回復:
情況1
在這里,我們考慮以下宣告:
EventHandler TestCase1 = []() {};//this is copy initialization
上面的陳述句使用復制初始化。
并從復制初始化的檔案中:
此外,復制初始化中的隱式轉換 必須
T直接從初始化器產生,而直接初始化 期望從初始化器到T構造器的引數的隱式轉換。
并且由于EventHandler不能直接從右側的初始化程式 lambda 生成,TestCase1根據上面參考的陳述句,第一種情況是不允許的。
案例2
在這里,我們考慮宣告,
EventHandler TestCase2([]() {});//this is direct initialization
上面使用直接初始化,并且由于有一個可用的隱式轉換(使用轉換建構式),這次根據上面參考的陳述句是允許的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/481811.html
上一篇:std::future可以在沒有獲取或等待的情況下導致核心轉儲嗎
下一篇:c :算術運算子多載
