我使以下函式成為我班級的成員:
template <typename... _Types>
void NotifyAllDelayed(_Types&&... _Args)
{
delay_runner->Add([=, this] { this->NotifyAll<_Types...>(std::forward<_Types>(_Args)...); });
}
我創建了這個,因為我不想讓自己重復:
delay_runner->Add([=, ¬ifications] { notifications->NotifyAll(specific_listener_ptr, &ISpecificUserDataListener::OnSpecificUserDataUpdated, 2022); });
// and
delay_runner->Add([=, ¬ifications] { notifications->NotifyAll(&ISpecificUserDataListener::OnSpecificUserDataUpdated, 3033); });
所以我可以寫:
notifications->NotifyAllDelayed(specific_listener_ptr, &ISpecificUserDataListener::OnSpecificUserDataUpdated, 9);
notifications->NotifyAllDelayed(&ISpecificUserDataListener::OnSpecificUserDataUpdated, 3033);
但是后來我得到了這些錯誤(MSVC,啟用了 C 20):
Build started...
1>------ Build started: Project: Forward, Configuration: Debug x64 ------
1>Forward.cpp
1> Forward.cpp(133,65): error C2665: 'std::forward': none of the 2 overloads could convert all the argument types
1>C:\Program Files\Microsoft Visual Studio\2022\Professional\VC\Tools\MSVC\14.33.31629\include\type_traits(1416,28): message : could be '_Ty (__cdecl ISpecificUserDataListener::* &&std::forward<void(__cdecl ISpecificUserDataListener::* )(int)>(void (__cdecl ISpecificUserDataListener::* &&)(int)) noexcept)(int)'
1> with
1> [
1> _Ty=void (__cdecl ISpecificUserDataListener::* )(int)
1> ]
1>C:\Program Files\Microsoft Visual Studio\2022\Professional\VC\Tools\MSVC\14.33.31629\include\type_traits(1410,28): message : or '_Ty (__cdecl ISpecificUserDataListener::* &&std::forward<void(__cdecl ISpecificUserDataListener::* )(int)>(void (__cdecl ISpecificUserDataListener::* &)(int)) noexcept)(int)'
1> with
1> [
1> _Ty=void (__cdecl ISpecificUserDataListener::* )(int)
1> ]
1> Forward.cpp(133,65): message : '_Ty (__cdecl ISpecificUserDataListener::* &&std::forward<void(__cdecl ISpecificUserDataListener::* )(int)>(void (__cdecl ISpecificUserDataListener::* &)(int)) noexcept)(int)': cannot convert argument 1 from 'void (__cdecl ISpecificUserDataListener::* const )(int)' to 'void (__cdecl ISpecificUserDataListener::* &)(int)'
1> with
1> [
1> _Ty=void (__cdecl ISpecificUserDataListener::* )(int)
1> ]
1> Forward.cpp(133,81): message : Conversion loses qualifiers
1>C:\Program Files\Microsoft Visual Studio\2022\Professional\VC\Tools\MSVC\14.33.31629\include\type_traits(1410,28): message : see declaration of 'std::forward'
1> Forward.cpp(132,1): message : while trying to match the argument list '(void (__cdecl ISpecificUserDataListener::* const )(int))'
1> Forward.cpp(178): message : see reference to function template instantiation 'void NotificationManager::NotifyAllDelayed<void(__cdecl ISpecificUserDataListener::* )(int),int>(void (__cdecl ISpecificUserDataListener::* &&)(int),int &&)' being compiled
1> Forward.cpp(133,37): error C2672: 'NotificationManager::NotifyAll': no matching overloaded function found
1> Forward.cpp(116,7): message : could be 'bool NotificationManager::NotifyAll(T *,_Fx &&,_Types &&...)'
1> Forward.cpp(133,37): message : 'bool NotificationManager::NotifyAll(T *,_Fx &&,_Types &&...)': expects 3 arguments - 1 provided
1> Forward.cpp(116): message : see declaration of 'NotificationManager::NotifyAll'
1> Forward.cpp(105,7): message : or 'bool NotificationManager::NotifyAll(_Fx &&,_Types &&...)'
1>Done building project "Forward.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
我用相同的代碼嘗試了 coliru,但它給出了另一個錯誤:
main.cpp: In instantiation of 'void NotificationManager::NotifyAllDelayed(_Types&& ...) [with _Types = {void (ISpecificUserDataListener::*)(int), int}]':
main.cpp:168:33: required from here
main.cpp:133:95: error: binding reference of type 'void (ISpecificUserDataListener::*&)(int)' to 'void (ISpecificUserDataListener::* const)(int)' discards qualifiers
133 | delay_runner->Add([=, this] { this->NotifyAll<_Types...>(std::forward<_Types>(_Args)...); });
這個錯誤是什么意思?
我該如何解決?
我的另一個具有更復雜的可變引數模板引數的模板函式(NotifyAll)作業得很好:
//primary template
template<typename> struct extract_class_from_member_function_ptr;
template <typename A, typename B, class... _Types>
struct extract_class_from_member_function_ptr<A(B::*)(_Types...)> {
using type = B;
};
template <class _Fx, class... _Types>
bool NotifyAll(_Fx&& _Func, _Types&&... _Args) {
using T = extract_class_from_member_function_ptr<_Fx>::type;
return ExecuteForListenerTypePerEntry(T::GetListenerType(), [&](IListener* listener) {
T* casted_listener = dynamic_cast<T*>(listener);
if (casted_listener) {
std::invoke(std::forward<_Fx>(_Func), casted_listener, std::forward<_Types>(_Args)...);
}
});
}
template <typename T, class _Fx, class... _Types>
bool NotifyAll(T* one_time_specific_listener, _Fx&& _Func, _Types&&... _Args) {
using BaseT = extract_class_from_member_function_ptr<_Fx>::type;
return ExecuteForListenerTypePerEntry(BaseT::GetListenerType(), one_time_specific_listener, [&](IListener* listener) {
BaseT* casted_listener = dynamic_cast<BaseT*>(listener);
if (casted_listener) {
std::invoke(std::forward<_Fx>(_Func), casted_listener, std::forward<_Types>(_Args)...);
}
});
}
我嘗試在 NotifyAllDelayed 上制作一些具有不同引數的變體,但這也沒有產生任何積極影響。
這是一個最小的作業示例,其中 NotifyAllDelayed 可以取消注釋并且代碼將運行:
#include <array>
#include <functional>
#include <iostream>
#include <queue>
#include <set>
#include <utility>
// code below doesn't matter VVVVVVVVVVVVVVVV
class DelayRunner
{
public:
using func_t = std::function<void(void)>;
private:
std::queue<func_t> queue;
public:
DelayRunner() : queue{} {}
~DelayRunner() {}
void Run() {
while (queue.size()) {
queue.front()();
queue.pop();
}
}
void Add(const func_t& func) {
queue.push(func);
}
};
enum ListenerType { LISTENER_TYPE_BEGIN, SPECIFIC_USER_DATA, LISTENER_TYPE_END };
class IListener {
public:
virtual ~IListener() {}
};
template<ListenerType type> class TypeAwareListener : public IListener {
public:
static ListenerType GetListenerType() {
return type;
}
};
class ISpecificUserDataListener : public TypeAwareListener<SPECIFIC_USER_DATA>
{
public:
virtual void OnSpecificUserDataUpdated(int userID) = 0;
};
class NotificationManager
{
private:
using listener_set = std::set<IListener*>;
std::array<listener_set, LISTENER_TYPE_END> listeners;
DelayRunner* delay_runner;
public:
NotificationManager(DelayRunner* delay_runner) : listeners{}, delay_runner{ delay_runner } {}
~NotificationManager() {}
void Register(ListenerType listenerType, IListener* listener) { listeners[listenerType].insert(listener); }
void Unregister(ListenerType listenerType, IListener* listener) { listeners[listenerType].erase(listener); }
bool ExecuteForListenerTypePerEntry(ListenerType listenerType, std::function<void(IListener* listeners)> code) {
listener_set& set = listeners[listenerType];
if (set.size() == 0) {
return false;
}
for (auto& entry : set) {
code(entry);
}
return true;
}
bool ExecuteForListenerTypePerEntry(ListenerType listenerType, IListener* one_time_specific_listener, std::function<void(IListener* listeners)> code) {
listener_set& set = listeners[listenerType];
if (one_time_specific_listener != nullptr) {
code(one_time_specific_listener);
}
for (auto& entry : set) {
if ((entry != one_time_specific_listener) && (entry != nullptr)) {
code(entry);
}
}
return (set.size() > 0) || (one_time_specific_listener != nullptr);
}
//primary template
template<typename> struct extract_class_from_member_function_ptr;
template <typename A, typename B, class... _Types>
struct extract_class_from_member_function_ptr<A(B::*)(_Types...)> {
using type = B;
};
template <class _Fx, class... _Types>
bool NotifyAll(_Fx&& _Func, _Types&&... _Args) {
using T = extract_class_from_member_function_ptr<_Fx>::type;
return ExecuteForListenerTypePerEntry(T::GetListenerType(), [&](IListener* listener) {
T* casted_listener = dynamic_cast<T*>(listener);
if (casted_listener) {
std::invoke(std::forward<_Fx>(_Func), casted_listener, std::forward<_Types>(_Args)...);
}
});
}
template <typename T, class _Fx, class... _Types>
bool NotifyAll(T* one_time_specific_listener, _Fx&& _Func, _Types&&... _Args) {
using BaseT = extract_class_from_member_function_ptr<_Fx>::type;
return ExecuteForListenerTypePerEntry(BaseT::GetListenerType(), one_time_specific_listener, [&](IListener* listener) {
BaseT* casted_listener = dynamic_cast<BaseT*>(listener);
if (casted_listener) {
std::invoke(std::forward<_Fx>(_Func), casted_listener, std::forward<_Types>(_Args)...);
}
});
}
// Above code doesn't matter ^^^^^^^^^^^^^^^^
// Because it works
// Question is about this code:
template <typename... _Types>
void NotifyAllDelayed(_Types&&... _Args)
{
delay_runner->Add([=, this] { this->NotifyAll<_Types...>(std::forward<_Types>(_Args)...); });
}
// code below doesn't matter VVVVVVVVVVVVVVVV
};
class GlobalUserDataListener : public ISpecificUserDataListener {
public:
virtual void OnSpecificUserDataUpdated(int userID) override {
std::cout << "GlobalUserDataListener called with userID: " << userID << std::endl;
}
};
class SpecificCallUserDataListener : public ISpecificUserDataListener {
public:
virtual void OnSpecificUserDataUpdated(int userID) override {
std::cout << "SpecificCallUserDataListener called with userID: " << userID << std::endl;
}
};
int main()
{
GlobalUserDataListener* global_listener_ptr{ new GlobalUserDataListener{} };
SpecificCallUserDataListener* specific_listener_ptr{ new SpecificCallUserDataListener{} };
DelayRunner* delay_runner{ new DelayRunner{} };
NotificationManager* notifications{ new NotificationManager{delay_runner} };
notifications->Register(global_listener_ptr->GetListenerType(), global_listener_ptr);
notifications->NotifyAll(&ISpecificUserDataListener::OnSpecificUserDataUpdated, 42);
notifications->NotifyAll(specific_listener_ptr, &ISpecificUserDataListener::OnSpecificUserDataUpdated, 28);
delay_runner->Add([=, ¬ifications] { notifications->NotifyAll(specific_listener_ptr, &ISpecificUserDataListener::OnSpecificUserDataUpdated, 2022); });
//notifications->NotifyAllDelayed(&ISpecificUserDataListener::OnSpecificUserDataUpdated, 9);
//notifications->NotifyAllDelayed(specific_listener_ptr, &ISpecificUserDataListener::OnSpecificUserDataUpdated, 2022);
std::cout << "Tick" << std::endl;
delay_runner->Run();
delete notifications;
delete delay_runner;
delete specific_listener_ptr;
delete global_listener_ptr;
return 0;
}
uj5u.com熱心網友回復:
第一:所有以下劃線后跟大寫字母的識別符號在所有背景關系中都保留給 C 實作,并且在用戶代碼中使用它們會導致未定義的行為。
我仍將繼續在答案中使用這些識別符號,以使問題的背景關系更易于識別。
它不起作用,因為operator()lambda 默認是const合格的。因此,參考閉包物件成員的左值也將被const限定。
例如,第二個引數9是NotifyAllDelayed型別的右值int。因此,將其傳遞給函式將推匯出_Typesto的相應元素int。在命名第二個元素的函式內部_Args是一個左值運算式 type int。
但是,當_Args在 lambda 內部參考時,它指的是相應的捕獲的閉包成員,因此當命名為運算式時,它的第二個元素是型別的左值,const int因為.constoperator()
然后你嘗試有效地呼叫std::forward<int>(/*lvalue of type const int*/)。編譯器抱怨這是不可能的,因為您試圖const從型別中洗掉 。
您需要標記 lambdamutable以使其編譯,但是它在語意上也沒有意義。您正在將所有內容復制_Args到 lambda 中。lambda body 不再指代函式外的物件,而是指閉包物件內的副本。這些物件始終由 lambda 擁有,無需根據傳遞給NotifyAllDelayed. 您可以決定傳遞std::move(_Args),在這種情況下,lambda 可能只被呼叫一次,或者只是傳遞_Args,呼叫時可能會產生額外的復制操作,但允許多次呼叫 lambda。一個更簡潔的解決方案是使用基于左值和右值多載struct的函式物件在這兩個變體之間進行選擇。operator()this
NotifyAll在任何情況下,都應該推匯出模板引數。手動指定它們會以微妙的方式破壞,例如,您的第二個多載通常不適用于顯式引數,因為它不希望T成為實際函式引數的型別(而不是T*)。
您只能通過將引數NotifyAllDelayed轉發到閉包中的副本而不是總是復制它們來利用引數的值類別。通過 lambda 而不是struct基于 - 的函式物件執行此操作需要 C 20 的 init-capture 包擴展:
delay_runner->Add([..._Args=std::forward<_Types>(_Args), this]() mutable { this->NotifyAll(/* as above */); });
(mutable如果您std::move在引數中選擇,則需要)
或者使用 C 20,您可以簡單地使用std::bind_frontwhich 來完成所有這些操作:
delay_runner->Add(std::bind_front([this](auto&&... args){
this->NotifyAll(std::forward<decltype(args)>(args)...);
}), std::forward<_Types>(_Args)...);
嵌套 lambda 僅用于解決NotifyAll. 不幸的是,目前語言/庫中不支持以更清晰的方式撰寫這個通用包裝 lambda。為它撰寫宏并不罕見。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/515154.html
標籤:C 模板
