Klaus Klaus - 1 year ago 79
C++ Question

template which takes a pack of type T

I have the following minimal code fragment which compiles and executes as expected:

template < class T, T... Chrs>
struct mystring
static auto c_str()
static char str[] = {Chrs..., 0};
return str;


template <class T, T... Chrs>
auto operator""_t()
return mystring<T, Chrs...>();

int main()
auto x = "Hallo"_t ;
std::cout << x.c_str() << std::endl;


Is it possible to write the template
in a way that it excepts:

auto x = mystring<'a','b','c'>();

but also

auto x = mystring< 1,2,3> ();

or any other type.

I have no idea how to write something like ( pseudo code ):

template < T ... Chrs> // how to define T here?
struct mystring
{ }

Also the following is not allowed:

template <typename T, T ...Chrs >
struct mystring<T...Chrs> {};

Answer Source

The same way you're doing it right now. Except instead of using T, where T is a template parameter, just use char directly:

template <char... Chrs>
struct mystring
    /* rest as before */

Of course this now only works for char and not wchar_t (but then again, so does the original)

You can generalize this by writing something like:

template <class T, T... Vals>
struct array { ... };

template <char... Chrs>
using mystring  = array<char, Chrs...>;

In C++17, we'll have template auto which would let you write:

template <auto... Vals>
struct array { /* .. */ };

and then it's up to you to verify that all the Vals are the same type. Perhaps via:

template <auto Val, decltype(Val)... Vals>
struct array { /* .. */ };
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download