簡體   English   中英

C++ 可變參數模板找出類型

[英]C++ variadic templates find out type

我有這些模板:

template<size_t DestinationVariableId, size_t SourceVariableId>
struct store {
    static constexpr size_t destinationVariableId = DestinationVariableId;
    static constexpr size_t sourceVariableId = SourceVariableId;
    static constexpr int instruction = 2;
};

template<size_t DestinationVariableId, size_t SourceVariableId>
struct add {
    static constexpr size_t destinationVariableId = DestinationVariableId;
    static constexpr size_t sourceVariableId = SourceVariableId;
    static constexpr int instruction = 3;
};

/-------------enable_if_else-------------
template<bool Cond, typename TrueType, typename FalseType>
struct enable_if_else;

template<typename TrueType, typename FalseType>
struct enable_if_else<true, TrueType, FalseType> {
    using type = TrueType;
};

template<typename TrueType, typename FalseType>
struct enable_if_else<false, TrueType, FalseType> {
    using type = FalseType;
};

//-------------static_list-------------
template<class ...Elements>
struct static_list {};

//-------------static_list_get-------------
template<size_t Idx, class List>
struct static_list_get;

template<size_t Idx, class FirstElement, class ...Elements>
struct static_list_get<Idx, static_list<FirstElement, Elements ...>>
    : static_list_get<Idx - 1, static_list<Elements ...>> {
};

template<class FirstElement, class ...Elements>
struct static_list_get<1, static_list<FirstElement, Elements ...>> {
    using type = FirstElement;
};

//-------------execute_s-------------
template<int index, class ...Commands>
struct execute_s;

template<int index, class ...Commands>
struct execute_s <index, static_list<Commands ...>> {
    static constexpr int value = enable_if_else < static_list_get<index, static_list<Commands ...>>::instruction == 1, add<0, 0>::instruction , store<1, 1>::instruction >;
};

在 execute_s 中,我想檢查給定索引處的命令是否屬於 add 或 store 類型,並返回給定 output。

如何在編譯時檢查模板結構 execute_s 中給定索引處的命令是什么類型的? enable_if_else < static_list_get<index, static_list<Commands...>>::instruction == 1, add<0, 0>::instruction, store<1, 1>::instruction >; 不起作用,因為從一般命令中不清楚::instruction。

::instruction是一個int ,因此您不能將其作為參數傳遞給enable_if_else ,至少作為一種類型。 您可以將它作為非類型模板參數傳遞,但實際上,您根本不需要enable_if_else 您可以像這樣初始化value

static constexpr int value = [] { 
    return static_list_get<index, static_list<Commands ...>>::instruction == 1 ? 
           add<0, 0>::instruction :
           store<1, 1>::instruction;
}();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM