2

Is it possible to append items to a std::initializer_list at compile time?

I am writing a struct to try to collect in a std::initializer_list a bunch of const char* names coming from a 3rd party lib which are associated to some specific types from the same lib as the names, but disconnected codewise (e.g. the names are not part of the types, they are not even in the same namespace).

This is the struct I am trying to write:

template < typename T, typename... Args >
struct S : S< T >, S< Args... >
{
    static auto
    get_names( )
    {
        // concatenation should go here
        // return S< T >::get_names() + S< Args >::get_names()...
        // or something similar
    }
};

template <>
struct S< lib::types::SpecificTypeA >
{
    static auto
    get_names( )
    {
        // the name is a const char * coming from the same 3rd party lib
        return { lib::names::name_of_specific_type_a };
    } 
};

I am using C++17.

nyarlathotep108
  • 5,275
  • 2
  • 26
  • 64
  • If you want to make a list of all names, it would be trivial to do without any templates: `{lib::names::name_of_specific_type_a, lib::names::name_of_specific_type_b, etc }`. What do you want to use your templates for? Should the first struct make a subset of names? – VLL Mar 05 '21 at 12:45
  • @vll I tried to extract the minimum viable example from a much larger code. I need a compile time list which is not always a list of all the types. – nyarlathotep108 Mar 05 '21 at 12:49
  • 1
    I don't think that it is feasible to operate with `std::initializer_list`. You could create `std::array` and concatenate them. It isn't complex. – ALX23z Mar 05 '21 at 12:54
  • Depending the variable names, you might be able to use a macro. https://stackoverflow.com/questions/1872220/is-it-possible-to-iterate-over-arguments-in-variadic-macros – VLL Mar 05 '21 at 12:58
  • 1
    `std::initializer_list` is a reference type. It's always backed by an array it binds to. The array is just like any temporary bound to a reference. It doesn't outlive function scope if bound there. Your approach is full of dangling references. – StoryTeller - Unslander Monica Mar 05 '21 at 14:09

1 Answers1

-3

As far as I know, you can't construct any object at compile time in C++.

No object can be constructed before the program starts.

We usually construct these objects at the beginning of main(). It doesn't affect the performance.

aleck099
  • 428
  • 2
  • 10