【问题标题】:Call template-function with types in a tuple (not values)使用元组中的类型(而非值)调用模板函数
【发布时间】:2023-02-02 20:07:25
【问题描述】:

我想为元组中的每种类型调用一个不带参数的模板函数。下面的代码准确地显示了意图是什么。

我的解决方案涉及制作一个 DataGroup() 的虚拟实例。我想避免这种情况,因为类型可能没有默认构造函数。

我试图改用std::declval<DataGroup>(),这导致 'std::declval': Symbol involving type with internal linkage not defined(在 msvc 中)。

#pragma once
#include <tuple>

template<typename T>
void do_something_based_on_the_type()
{
    // ...
}

template<template <typename...> typename Tuple, typename... Ts>
void do_something_based_on_the_types_in_a_tuple(Tuple<Ts...>)
{
    (do_something_based_on_the_type<Ts>(), ...);
}

void some_code()
{
    struct Dataset1 {};
    struct Dataset2 {};
    struct Dataset3 {};
    using DataGroup = std::tuple<Dataset1, Dataset2, Dataset3>;

    do_something_based_on_the_types_in_a_tuple(DataGroup()); // -> ugly? requires a dummy instantiation of the tuple
}


【问题讨论】:

    标签: c++ templates c++20 variadic-templates


    【解决方案1】:

    我的解决方案是使用辅助函数进行类型推导。这个辅助函数将获取一个指向 DataGroup 实例的指针,并使用它来推断元组中的类型。

    template<typename T>
    void do_something_based_on_the_type()
    {
        // ...
    }
    
    template<typename T>
    void do_something_based_on_the_types_in_a_tuple_helper(T* dataGroup)
    {
        std::apply([](auto&&... args){ (do_something_based_on_the_type<decltype(args)>(), ...); }, *dataGroup);
    }
    
    void some_code()
    {
        struct Dataset1 {};
        struct Dataset2 {};
        struct Dataset3 {};
        using DataGroup = std::tuple<Dataset1, Dataset2, Dataset3>;
    
        DataGroup dataGroup;
        do_something_based_on_the_types_in_a_tuple_helper(&dataGroup);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-01
      相关资源
      最近更新 更多