【问题标题】:create std::tuple using compile-time types and a run-time function使用编译时类型和运行时函数创建 std::tuple
【发布时间】:2021-11-19 01:55:48
【问题描述】:

我正在尝试构建(在运行时)一个其类型在编译时已知的元组。 我想我已经很接近了:

#include <tuple>

// This is defined elsewhere
template<typename T>
T* create_obj();

template<typename ...Ts>
auto create_tuple()
{
    std::tuple_cat(
        (std::make_tuple( create_obj<std::tuple_element<Idx, Ts...>() ), ...) // Idx?
    );
}

示例用法可能是:

struct A{};
struct B{};
struct C{};

std::tuple<A*, B*, C*> = create_tuple<A, B, C>();

我被困在如何在编译时迭代 Idx... 也许是 std::index_sequence?

【问题讨论】:

    标签: c++ templates metaprogramming


    【解决方案1】:

    我不确定我是否正确理解了这个问题,因为我不明白你为什么要迭代Idx,为什么要使用tuple_elementtuple_cat。我想你只想调用make_tuple 来返回一个元组,其元素是通过create_obj 创建的:

    #include <tuple>
    
    template<typename T>
    T* create_obj() { return new T{};}
    
    template<typename ...Ts>
    auto create_tuple()
    {
        return std::make_tuple( create_obj<Ts>() ...);
    }
    
    struct A{};
    struct B{};
    struct C{};
    
    int main() {
        std::tuple<A*, B*, C*> a = create_tuple<A, B, C>();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-07
      • 2021-10-16
      • 1970-01-01
      • 1970-01-01
      • 2019-06-15
      • 2020-04-21
      相关资源
      最近更新 更多