簡體   English   中英

C ++模板元編程 - 根據運行時輸入返回一個類型

[英]C++ template metaprogramming - return a type based on runtime input

我正在嘗試創建一個模板化的向量,其中模板類型由運行時參數確定。 我知道模板的東西是在運行之前完成的,基本上我試圖將運行時輸入匯集到一些先前選擇的編譯時類型中。 這是我希望能夠做的一個高級示例。

for (int i = 0; i < 2; ++i)
{
    std::vector<getRunTimeT(i)> v;

    // Do stuff with v
}

因此,應使用運行時輸入選擇的類型初始化向量。

到目前為止,我已經得出結論,需要專門的模板元編程,並且我有使用compile -time參數執行我需要的功能:

template<int i>
struct getCompileTimeT
{
    typedef int type; // Base case, not expected to occur.
};

template<>
struct getCompileTimeT<0>
{
    typedef int type;
};

template<>
struct getCompileTimeT<1>
{
    typedef float type;
};

所以我可以這樣做:

std::vector<getCompileTimeT(1)> type; // Creates a vector of floats

因此,我需要以某種方式將編譯時方面與從預定義模板類型中選擇正確類型的函數進行橋接。 這是一個( 非法 )示例,說明我如何設想這種橋接功能:

// Illegal demonstrative desired functionality
_type_ getRunTimeT(int select)
{
    if (select == 0) return getCompileTimeT<0>;
    else if (select == 1) return getCompileTimeT<1>;
}

所以基本上我正在尋找在編譯時功能和我所說的運行時功能之間“橋接”的東西。 這可能嗎?

謝謝你提供的所有幫助!

編輯:附加信息:

感謝您迄今為止的解決方案; 他們在幫助我更徹底地理解這一點方面非常有用。 我想提供一個API類型的函數,用戶可以操作或使用一個類型,從他們的角度看是“動態的”。 例如:

UserClass::function()
{
    for (int i = 0; i < 2; ++i)
    {
        // getType() is something that may be a template parameter
        myFunc<getType(i)>();
    }
}

template<class T>
void UserClass::myFunc()
{
    std::vector<T> v;

    // Now the user has a vector to play with in their member function.
}

試試這個

template <class T>
void do_stuff()
{
    std::vector<T> v;
    // Do stuff with v
}

void do_suff_dispatch(int i)
{
    switch (i)
    {
        case 0:
            do_stuff<int>();
            break;
        case 1:
            do_stuff<float>();
            break;
    }
}

for (int i = 0; i < 2; ++i)
{
    do_suff_dispatch(i);
}

您可以考慮使用boost :: variant <>作為保留通用值存儲的類型:

http://www.boost.org/doc/libs/1_55_0/doc/html/variant/tutorial.html

這個想法如下:

typedef boost::variant<
    getCompileTimeT<0>,
    getCompileTimeT<1>
> variant_type;

variant_type getRunTimeT(int select)
{
    if (select == 0) return variant_type(getCompileTimeT<0>());
    else if (select == 1) return variant_type(getCompileTimeT<1>());
}

在這個階段,您可以依賴variant的訪問者模式(在變體的教程中描述)來進行類型安全值調度。

根據您的應用程序和一些模板魔法(特別是在c ++ 11上),您可以在getCompileTimeT<>模板參數范圍內簡明地定義原始變體類型(因此無需明確枚舉所有模板參數)。

暫無
暫無

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

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