Search code examples
c++templatesmetaprogramming

create std::tuple using compile-time types and a run-time function


I'm trying to build (at runtime) a tuple whose types are known at compile-time. I've gotten it pretty close I think:

#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?
    );
}

Example usage might be:

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

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

I'm stuck on how to iterate Idx at compile-time... Maybe std::index_sequence?


Solution

  • I am not sure if I correctly understand the question, because I dont understand why you want to iterate Idx, why use tuple_element or tuple_cat. I think you just want to call make_tuple to return a tuple whose elements are created via 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>();
    }