我想將指向引數包引數副本的指標存盤在tuple中。這是代碼:
struct FDead {};
struct FAlive {};
struct FBossDead final : FDead {};
struct FBossAlive final : FAlive {};
template<typename... TStates>
struct TContext
{
using FTuple = std::tuple<TStates*...>;
template<typename... TSubStates>
explicit TContext(TSubStates&&... InStates)
{
static_assert(sizeof...(TStates) == sizeof...(TSubStates));
// FIXME: Check if TSubStates are actually sub-types of TStates
//static_assert(((std::is_base_of_v<TStates, TSubStates> || ...) && ...));
States = FTuple{(new TSubStates{ InStates }, ...)};
}
FTuple States;
};
void Test()
{
TContext<FAlive, FDead> Context
{
FBossAlive{},
FBossDead{}
};
}
如您所見,FBossDeadextendsFDead和FBossAliveextends FAlive。TContext是使用基型別作為模板引數創建的,但是我發送了我想要復制的它們的子型別,然后將指向它們的指標存盤在States元組中。
我收到了這個編譯錯誤:
[C2440] '<function-style-cast>': cannot convert from 'initializer list' to 'std::tuple<PCF::SubClass::FAlive *,PCF::SubClass::FDead *>'
我相信這是因為這個 fold 運算式:
(new TSubStates{ InStates }, ...)
計算結果為 a initializer_list,而不是元組(因為逗號,我相信)但我不知道如何解決這個問題。任何幫助都感激不盡!
nb 我需要存盤副本,我無法更改建構式簽名以接受一組指標。
uj5u.com熱心網友回復:
這里不需要折疊運算式。常規的引數包擴展就可以了。
此外,雖然對于您發布的示例并非絕對必要,但std::forward<>在處理轉發參考(即InStates)時使用是一個好習慣。
States = FTuple{ new TSubStates{ std::forward<TSubStates>(InStates) }... };
但你也可以在初始化串列中這樣做:
template<typename... TSubStates>
explicit TContext(TSubStates&&... InStates)
: States{ new TSubStates{ std::forward<TSubStates>(InStates) }... } {
// FIXED: Check if TSubStates are actually sub-types of TStates
// But this is redundant, as the pointer assignment itself would fail.
static_assert((std::is_base_of_v<TStates, TSubStates> && ...));
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/484068.html
上一篇:vector<unique_ptr<Base>>使用Derived的初始化串列
下一篇:如何從列舉類中獲取隨機值?
