Home > Back-end >  A compile time evaluated char ()[N]
A compile time evaluated char ()[N]

Time:06-07

I am using a library function which is invoked through a macro

It turns out that I cannot pass a variable using that function because, the library function must be invoked through a Macro:

 RUN_LIB1(app, url) app.run<get_parameter(url)>(url)

The problem is that get_parameter has the following signature

  template<unsigned N>
 constexpr uint64_t get_parameter_tag(char (&url)[N])

while the run method has the following signature

 run(std::string&& url)

So the Macro works fine if I do :

 RUN_LIB(app, "test")

but not when I e.g. store the compile time constructed char in a variable.. like:

 template<unsigned N> 
   call_lib(char (&url) [N]){

       RUN_LIB(app,url) // error: no matching member function for call to 'run'
     
   }
   
  call_lib("Test"); // wont compile

I am thinking on passing a std::array<char,N> to my call_lib. Then, I want to convert that std::array to a char[N] , but can that be done at compile time? Or is there any other solution to make this work.

The function get_parameter is a recursive function iterating through the size of the url

CodePudding user response:

Instead of passing const char*, pass sequence of char:

template<char... Cs> 
void call_lib(char_sequence<char, Cs...> seq){
    RUN_LIB(app, seq.c_str);
}

gcc/clang have an extension to allow to build UDL from literal string:

template<typename Char, Char... Cs>
struct char_sequence
{
    static constexpr const Char c_str[] = {Cs..., 0};
};

// That template uses the extension
template<typename Char, Char... Cs>
constexpr auto operator"" _cs() -> char_sequence<Cs...> {
    return {};
}

See my answer from String-interning at compiletime for profiling to have MAKE_STRING macro if you cannot used the extension (Really more verbose, and hard coded limit for accepted string length).

Then the call would be

call_lib("Test"_cs);
  • Related