繁体   English   中英

使用可变参数类模板的模板参数调用可变参数函数模板?

[英]Call variadic function template with template parameters of variadic class template?

给定一个可变参数类模板,如何使用该类的模板参数调用可变参数函数模板?

例子:

template <typename T0,typename... Ts>
    void test_variadic()
{
    std::cout<<typeid(T0).name()<<std::endl;
    if constexpr (sizeof...(Ts) > 0)
        test_variadic<Ts...>();
}

template<typename T> // T is variadic class template
    void f0()
{
    // test_variadic<T...>(); // Call 'test_variadic' with underlying template parameter types of T? (In this example case `test_variadic<float,int>`)
}

template<typename ...T>
    class VariadicClass
{};

int main(int argc,char *argv[])
{
    f0<VariadicClass<float,int>>();
    return EXIT_SUCCESS;
}

为实现f0就是我失踪,我想它来调用test_variadic<float,int>通过确定从模板参数列表T自动使用它调用test_variadic 我怎么做?

我找到了一个适用于元组的解决方案:

#include <tuple>

template <typename T0,typename... Ts>
    void test_variadic()
{
    std::cout<<typeid(T0).name()<<std::endl;
    if constexpr (sizeof...(Ts) > 0)
        test_variadic<Ts...>();
}

int main(int argc, char **argv)
{
    std::tuple<int, float> tp;
    std::apply([](auto &&... args) { test_variadic<decltype(args)...>(); }, tp);
    return 0;
}

但就我而言,我没有任何实际参数或对象,只有类型,因此 lambda 解决方案不起作用。

首选使用现代 C++ 的解决方案。

您可以将具有部分特化的类模板声明为:

// primary template (might implement it with default behavior)
template <typename T> struct test_variadic_impl;

// partial specialization for variadic class template
template <template <typename...> typename C, typename... Args>
struct test_variadic_impl<C<Args...>> {
    static auto call() {
        return test_variadic<Args...>();
    }
};

然后像这样使用它:

template<typename T> // T is variadic class template
    void f0()
{
    test_variadic_imple<T>::call();
}

居住

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM