簡體   English   中英

每種可變參數模板的調用權模板專門化

[英]Call right template specialization for each type of a variadic template

我有一個函數foo() ,它接受類型T...的列表,並針對傳入的向量的每個元素調用另一個(模板化的)函數do_stuff() 。更具體地說,我們遍歷向量(長度sizeof...(T) ),並想對vector[i]調用do_stuff<Ti>() ,其中TiT...的第i個類型T...

該信息在編譯時可用,所以我想這是可能的,但是我們如何做到這一點呢?

#include <iostream>
#include <string>
#include <vector>
#include <cassert>

template <typename T>
T do_stuff(int param);

template <>
int do_stuff(int param)
{
    return int(100);
}

template <>
std::string do_stuff(int param)
{
    return std::string("foo");
}

template <typename... T>
void foo(const std::vector<int>& p)
{
    assert(p.size() == sizeof...(T));
    for (int i = 0; i < p.size(); ++i)
    {
        // Won't compile as T is not specified:
        //do_stuff(p[i]);
        // How do we choose the right T, in this case Ti from T...?
    }
}

int main()
{
    std::vector<int> params = { 0,1,0,5 };
    foo<int, std::string, std::string, int>(params);
}

您可以使用C ++ 17折疊表達式:

template <typename... T>
void foo(const std::vector<int>& p)
{
    assert(p.size() == sizeof...(T));

    std::size_t i{};
    (do_stuff<T>(p[i++]), ...);
}

Godbolt.org上的實時示例


另外,您可以使用std::index_sequence避免使用可變的i變量:

template <typename... T>
void foo(const std::vector<int>& p)
{
    assert(p.size() == sizeof...(T));

    [&p]<auto... Is>(std::index_sequence<Is...>)
    {
        (do_stuff<T>(p[Is]), ...);
    }(std::index_sequence_for<T...>{});
}

Godbolt.org上的實時示例

如下呢?

template <typename ... T>
void foo (std::vector<int> const & p)
{
    assert(p.size() == sizeof...(T));

    using unused = int[];

    std::size_t  i{ 0u };

    (void)unused { 0, ((void)do_stuff<T>(p[i++]), 0)... };
}

如果可以使用C ++ 17,請參見Vittorio Romeo的答案,以獲取更優雅,更簡潔的解決方案。

暫無
暫無

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

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