C++11: Initialize constexpr char array with another constexpr char array - c++

I would like to initialize constexpr char[] member with another constexpr char [] member. Is it possible to do in C++11 or above?
#include <iostream>
struct Base {
static constexpr char ValueOne[] = "One";
static constexpr char ValueTwo[] = "Two";
};
template <typename T>
struct ValueOneHolder {
static constexpr char Value[] = T::ValueOne; // << How can one initialize this?
};
int main() {
std::cout << ValueOneHolder<Base>::Value << std::endl;
return 0;
}

I would like to initialize constexpr char[] member with another constexpr char [] member. Is it possible to do in C++11 or above?
Starting from C++14 you can use std::make_index_sequence and std::index_sequence.
If it's OK for you works in a ValueOneHolder specialization, you first can develop a constexpr function that, given a C-style array, return the size of the array
template <typename T, std::size_t N>
constexpr std::size_t getDim (T const (&)[N])
{ return N; }
Nest you can declare ValueOneHolder adding a second template parameter with a default value that is an index sequence corresponding to T::ValueOne
template <typename T,
typename = std::make_index_sequence<getDim(T::ValueOne)>>
struct ValueOneHolder;
and last the easy part: the partial specialization with initialization
template <typename T, std::size_t ... Is>
struct ValueOneHolder<T, std::index_sequence<Is...>>
{ static constexpr char Value[] = { T::ValueOne[Is] ... }; };
Don't forget the following line, outside the struct
template <typename T, std::size_t ... Is>
constexpr char ValueOneHolder<T, std::index_sequence<Is...>>::Value[];
The following is a full C++14 compiling example
#include <utility>
#include <iostream>
struct Base
{
static constexpr char ValueOne[] = "One";
static constexpr char ValueTwo[] = "Two";
};
template <typename T, std::size_t N>
constexpr std::size_t getDim (T const (&)[N])
{ return N; }
template <typename T,
typename = std::make_index_sequence<getDim(T::ValueOne)>>
struct ValueOneHolder;
template <typename T, std::size_t ... Is>
struct ValueOneHolder<T, std::index_sequence<Is...>>
{ static constexpr char Value[] = { T::ValueOne[Is] ... }; };
template <typename T, std::size_t ... Is>
constexpr char ValueOneHolder<T, std::index_sequence<Is...>>::Value[];
int main()
{
std::cout << ValueOneHolder<Base>::Value << std::endl;
}
If you want a C++11, you can develop a substitute for std::make_index_sequence and std::index_sequence.

In this particular example you may declare Value as the following:
template <typename T>
struct ValueOneHolder {
static constexpr auto Value = T::ValueOne; // << How can one initialize this?
};
Please note, GCC will fail to link this example unless you switch to -std=c++17 or add the folloing lines in a source file.
constexpr char Base::ValueOne[];
constexpr char Base::ValueTwo[];
With C++14 it is also possible to make a constexpr copy of a constexpr string (or its substring), as shown in example below:
template<typename CharT, size_t Size>
struct basic_cestring {
using value_type = CharT;
template<size_t... I> constexpr
basic_cestring(const char* str, index_sequence<I...>)
: _data{str[I]...} {}
inline constexpr operator const CharT* () const { return _data; }
const CharT _data[Size + 1];
};
template<size_t Size>
struct cestring : public basic_cestring<char, Size> {
using index = make_index_sequence<Size>;
constexpr cestring(const char* str)
: basic_cestring<char, Size>(str, index{}) {}
};

Related

Accepting std::array of char of any size as non type template parameter

This is probably a weird use case, but I am trying to hack around the fact string literals can not be used as arguments to templates using std::array<char, N> as non template type parameter.
This works but with extreme limitation that all strings must be of same length(I could use MAX_STR_LEN=100 or whatever and make all arrays that size, but that feels ugly...).
Is there a way to make this code work so that different size std::arrays can be accepted as template parameter?
#include <iostream>
#include <array>
#include <tuple>
#include <boost/mp11/algorithm.hpp>
#include <boost/mp11/tuple.hpp>
// I wish that this 6 is not fixed... but IDK how to fix it, maybe concept(IDK if concepts can be used as "types" on NTTP.
template <typename Type, std::array<char, 6> val_val>
struct TypeToValues
{
using type = Type;
static constexpr const char* val = val_val.data();
};
template <std::size_t Sz, std::size_t... Is>
constexpr std::array<char, Sz>
arrayify(const char (&arr)[Sz], std::index_sequence<Is...>)
{
return {{arr[Is]...}};
}
template <std::size_t Sz>
constexpr std::array<char, Sz> arrayify(const char (&arr)[Sz])
{
return arrayify(arr, std::make_index_sequence<Sz>());
}
struct HelloType{
};
struct YoloType{
};
int main(){
std::tuple<
TypeToValues<HelloType, arrayify("Hello")>,
TypeToValues<YoloType, arrayify("Yolo!")>> mapping;
boost::mp11::tuple_for_each(mapping, []<typename T>(const T&){
if constexpr(std::is_same_v<typename T::type, HelloType>){
std::cout << "HelloType says: " << T::val << std::endl;;
}
if constexpr(std::is_same_v<typename T::type, YoloType>){
std::cout << "YoloType says: " << T::val << std::endl;;
}
});
}
Sure, why not use a requires requires clause?
template <typename Type, auto val_val>
requires requires { { val_val.data() } -> std::same_as<char const*>; }
struct TypeToValues
{
// ...
Example.
You could also write a constraint that only specifically std::array<char, N> satisfy:
template<class> constexpr bool is_array_of_char_v = false;
template<unsigned N> constexpr bool is_array_of_char_v<std::array<char, N>> = true;
template<class T> concept ArrayOfChar = requires { is_array_of_char_v<T>; };
template <typename Type, ArrayOfChar auto val_val>
struct TypeToValues
{
// ...
But that feels excessively restrictive; you'll want to accept static string types in future.

how to initialize a static constexpr member of std::vector<std::string> in c++11?

I'm trying to initialize a static constexpr std::vector of std::strings inside my class Foo. I will later use the address of its elements.
class Foo {
public:
static constexpr std::vector<std::string> a = {"a", "bc", "232"}; // not working, constexpr variable not literal ....
const std::vector<std::string> a = {"a", "bc", "232"}; // this works
}
using c++11, thanks.
I can live with const instead of constexpr. but it's a little bit odd that there's no way to do this
It's good you can live with const but, just for fun, I show you a way to make a better-than-nothing constexpr static member that uses std::array instead of std::vector and (again) std::array instead of std::string.
Unfortunately you're using C++11, so no std::index_sequence/std::make_index_sequence (available starting from C++14) but I add a C++11 substitute in the following full example.
If you know a superior limit for the length of the strings you want use in the constexpr member, say 9 (3 in you example), you can define a fakeString type as follows
using fakeString = std::array<char, 10u>;
Observe that the size of the std::array is max-length plus one (plus the final zero).
Now you can define foo as follows
struct foo
{
static constexpr std::array<fakeString, 3u> a
{{ fs("a"), fs("bc"), fs("232") }};
};
constexpr std::array<fakeString, 3u> foo::a;
where fs() is a constexpr function that return a fakeString given a C-style array of char and uses a fsh() helper functions
The fs() and fsh() functions are as follows
template <std::size_t ... Is, std::size_t N>
constexpr fakeString fsh (indexSequence<Is...> const &, char const (&s)[N])
{ return {{ s[Is]... }}; }
template <std::size_t N>
constexpr fakeString fs (char const (&s)[N])
{ return fsh(makeIndexSequence<N>{}, s); }
Now you can use foo::a as follows
for ( auto const & fakeS : foo::a )
std::cout << fakeS.data() << std::endl;
Observe that you have to call the data() method that return a char *, that is a C-style string.
I repeat: just for fun.
The following is a full compiling C++11 example
#include <array>
#include <iostream>
template <std::size_t...>
struct indexSequence
{ using type = indexSequence; };
template <typename, typename>
struct concatSequences;
template <std::size_t... S1, std::size_t... S2>
struct concatSequences<indexSequence<S1...>, indexSequence<S2...>>
: public indexSequence<S1..., ( sizeof...(S1) + S2 )...>
{ };
template <std::size_t N>
struct makeIndexSequenceH
: public concatSequences<
typename makeIndexSequenceH<(N>>1)>::type,
typename makeIndexSequenceH<N-(N>>1)>::type>::type
{ };
template<>
struct makeIndexSequenceH<0> : public indexSequence<>
{ };
template<>
struct makeIndexSequenceH<1> : public indexSequence<0>
{ };
template <std::size_t N>
using makeIndexSequence = typename makeIndexSequenceH<N>::type;
using fakeString = std::array<char, 10u>;
template <std::size_t ... Is, std::size_t N>
constexpr fakeString fsh (indexSequence<Is...> const &, char const (&s)[N])
{ return {{ s[Is]... }}; }
template <std::size_t N>
constexpr fakeString fs (char const (&s)[N])
{ return fsh(makeIndexSequence<N>{}, s); }
struct foo
{
static constexpr std::array<fakeString, 3u> a
{{ fs("a"), fs("bc"), fs("232") }};
};
constexpr std::array<fakeString, 3u> foo::a;
int main ()
{
for ( auto const & fakeS : foo::a )
std::cout << fakeS.data() << std::endl;
}

Initializing a const vector of pointers to array at compile time using templates

The following class will not compile under C++11; the loop as it stands can only be executed at runtime and so one gets a "char(*)[i] is a variably-modified type" error from the template class static function call within the loop:
#include <cstddef>
#include <vector>
template <std::size_t N>
class Foo
{
private:
const std::vector<char(*)[]> bar = bar_init();
static std::vector<char(*)[]> bar_init()
{
std::vector<char(*)[]> init;
for (size_t i = N; i > 0; i >>= 1)
{
auto ptr_to_array = MyClass<char(*)[i]>::static_return_ptr_to_array();
init.emplace_back(reinterpret_cast<char(*)[]>(ptr_to_array));
}
return init;
}
};
Is there a way I can accomplish the same effect using templates within the initialization function? That is to say, initialize "bar" of size log2(N) at "Foo" class instantiation as a const vector of pointers to array of char with each vector element containing e.g. for N=32 the output of:
MyClass<char(*)[32]>::static_return_ptr_to_array();
MyClass<char(*)[16]>::static_return_ptr_to_array();
MyClass<char(*)[8]>::static_return_ptr_to_array();
//etc...
something like ( in c++11 )
template<int I>
struct tag{};
void init( std::vector<char(*)[]>& result, tag<0> ){}
template<int I>
void init( std::vector<char(*)[]>& result, tag<I> )
{
auto ptr_to_array = MyClass<char(*)[I]>::static_return_ptr_to_array;
result.emplace_back(reinterpret_cast<char(*)[]>(ptr_to_array));
init(result,tag<(I>>1)>{});
}
template <std::size_t N>
class Foo
{
private:
const std::vector<char(*)[]> bar = bar_init();
static std::vector<char(*)[]> bar_init()
{
std::vector<char(*)[]> result;
init( result, tag<N>{} );
return result;
}
};
in c++17 this can be further simplified with an if constexpr and no tag<>. Moreover, note that std::vector<char(*)[]> is not portable because vector needs a complete type.
I think the crucial insight here, is that you can't write:
int i = ?? // automatic variable
auto val = MyClass<char(*)[i]>::static_return_ptr_to_array()
... template arguments have to be constants.
What you can do is something like:
const std::unordered_map<int,???> allocator_map = {
{1, MyClass<char(*)[1]>::static_return_ptr_to_array},
{2, MyClass<char(*)[2]>::static_return_ptr_to_array},
{4, MyClass<char(*)[4]>::static_return_ptr_to_array},
{8, MyClass<char(*)[8]>::static_return_ptr_to_array},
...
};
and then
const auto it = allocator_map.find(i);
if (it == allocator_map.end())
// throw error
auto val = (it->second)();
Basically, the idea is that you have a static array of allocator functions, and then index into it. (There may be clever ways of using templates to initialize the map. I probably would just write it out by hand though - possibly using a preprocessor macro).
If you define index container type traits (or you use std::index_sequence, unfortunately available only starting from C++14)
template <std::size_t ...>
struct indexList
{ };
and you define a type traits to extract a sequence of decreasing power of two
template <std::size_t, typename>
struct iLH;
template <std::size_t N, std::size_t ... Is>
struct iLH<N, indexList<Is...>> : public iLH<(N >> 1), indexList<Is..., N>>
{ };
template <std::size_t ... Is>
struct iLH<0U, indexList<Is...>>
{ using type = indexList<Is...>; };
template <std::size_t N>
struct getIndexList : public iLH<N, indexList<>>
{ };
template <std::size_t N>
using getIndexList_t = typename getIndexList<N>::type;
should be possible write your Foo simply as
template <std::size_t N>
class Foo
{
private:
const std::vector<char **> bar = bar_init (getIndexList_t<N>{});
template <std::size_t ... Is>
static std::vector<char **> bar_init (indexList<Is...> const &)
{
std::vector<char **> init { MyClass<char(*)[Is]>::getPtr()... };
return init;
}
};
(supposing a static getPtr() method in MyClass) that return a char ** and a bar vector of char **).
The following is a full compiling example
template <typename T>
struct MyClass;
template <std::size_t Dim>
struct MyClass<char(*)[Dim]>
{
static char ** getPtr ()
{ static char ach[Dim]; static char * ret { ach } ; return &ret; }
};
template <std::size_t ...>
struct indexList
{ };
template <std::size_t, typename>
struct iLH;
template <std::size_t N, std::size_t ... Is>
struct iLH<N, indexList<Is...>> : public iLH<(N >> 1), indexList<Is..., N>>
{ };
template <std::size_t ... Is>
struct iLH<0U, indexList<Is...>>
{ using type = indexList<Is...>; };
template <std::size_t N>
struct getIndexList : public iLH<N, indexList<>>
{ };
template <std::size_t N>
using getIndexList_t = typename getIndexList<N>::type;
template <std::size_t N>
class Foo
{
private:
const std::vector<char **> bar = bar_init (getIndexList_t<N>{});
template <std::size_t ... Is>
static std::vector<char **> bar_init (indexList<Is...> const &)
{
std::vector<char **> init { MyClass<char(*)[Is]>::getPtr()... };
return init;
}
};
int main ()
{
Foo<32U> f32;
}

Want kind of constexpr switch case on type

I am currently doing this trick to have a cstring based on a type:
template<class ListT> static char constexpr * GetNameOfList(void)
{
return
std::conditional<
std::is_same<ListT, LicencesList>::value, "licences",
std::conditional<
std::is_same<ListT, BundlesList>::value, "bundles",
std::conditional<
std::is_same<ListT, ProductsList>::value, "products",
std::conditional<
std::is_same<ListT, UsersList>::value, "users",
nullptr
>
>
>
>;
}
But this code is not very good-looking, and if we want to check more types, this could be unreadable. Is it a way to do the same thing as if there were a switch case block?
Actually, the code is more complicated than that, because std::conditional need some type, so we need some class to do the trick:
struct LicenceName { static char constexpr * value = "licences"; };
for example.
I think it would be easier using template specialization
Example code:
#include <iostream>
struct A{};
struct B{};
struct C{};
struct D{};
template<typename T> constexpr const char* GetNameOfList();
//here you may want to make it return nullptr by default
template<>constexpr const char* GetNameOfList<A>(){return "A";}
template<>constexpr const char* GetNameOfList<B>(){return "B";}
template<>constexpr const char* GetNameOfList<C>(){return "C";}
int main(){
std::cout << GetNameOfList<A>() << '\n';
std::cout << GetNameOfList<B>() << '\n';
std::cout << GetNameOfList<C>() << '\n';
//std::cout << GetNameOfList<D>() << '\n'; //compile error here
}
You don't need to resort to metaprogramming, plain ifs work just fine:
template<class ListT>
constexpr char const *GetNameOfList() {
if(std::is_same<ListT, A>::value) return "A";
if(std::is_same<ListT, B>::value) return "B";
if(std::is_same<ListT, C>::value) return "C";
if(std::is_same<ListT, D>::value) return "D";
return nullptr;
}
See it live on Coliru
You could create constexpr array of strings plus tuple of list types to create mapping list type -> index -> name (if you need the mapping index -> types containing strings just use tuple instead of array). c++17 approach could look as follows:
#include <type_traits>
#include <tuple>
#include <utility>
#include <iostream>
struct LicencesList{};
struct BundlesList{};
struct ProductsList{};
struct UsersList{};
using ListTypes = std::tuple<LicencesList, BundlesList, ProductsList, UsersList>;
constexpr const char *NameList[] = {"licences", "bundles", "products", "users"};
template <class Tup, class, class = std::make_index_sequence<std::tuple_size<Tup>::value>>
struct index_of;
template <class Tup, class T, std::size_t... Is>
struct index_of<Tup, T, std::index_sequence<Is...>> {
static constexpr std::size_t value = ((std::is_same<std::tuple_element_t<Is, Tup>, T>::value * Is) + ...);
};
template<class ListT> static const char constexpr * GetNameOfList(void) {
return NameList[index_of<ListTypes, ListT>::value];
}
int main() {
constexpr const char *value = GetNameOfList<BundlesList>();
std::cout << value << std::endl;
}
[live demo]
If you want to maintain c++11 compatibility the approach would be just a little bit longer (I used here Casey's answer to implement index_of structure):
#include <type_traits>
#include <tuple>
#include <iostream>
struct LicencesList{};
struct BundlesList{};
struct ProductsList{};
struct UsersList{};
using ListTypes = std::tuple<LicencesList, BundlesList, ProductsList, UsersList>;
constexpr const char *NameList[] = {"licences", "bundles", "products", "users"};
template <class Tuple, class T>
struct index_of;
template <class T, class... Types>
struct index_of<std::tuple<T, Types...>, T> {
static const std::size_t value = 0;
};
template <class T, class U, class... Types>
struct index_of<std::tuple<U, Types...>, T> {
static const std::size_t value = 1 + index_of<std::tuple<Types...>, T>::value;
};
template<class ListT> static const char constexpr * GetNameOfList(void) {
return NameList[index_of<ListTypes, ListT>::value];
}
int main() {
constexpr const char *value = GetNameOfList<BundlesList>();
std::cout << value << std::endl;
}
[live demo]

Sum Nested Template Parameters at Compile Time

I'm looking for a better way to calculate the sum of numeric template parameters associated with nested template classes. I have a working solution here, but I want to do this without having to create this extra helper template class DepthCalculator and partial specialization DepthCalculator<double,N>:
#include <array>
#include <iostream>
template<typename T,size_t N>
struct DepthCalculator
{
static constexpr size_t Calculate()
{
return N + T::Depth();
}
};
template<size_t N>
struct DepthCalculator<double,N>
{
static constexpr size_t Calculate()
{
return N;
}
};
template<typename T,size_t N>
class A
{
std::array<T,N> arr;
public:
static constexpr size_t Depth()
{
return DepthCalculator<T,N>::Calculate();
}
// ...
// Too many methods in A to write a separate specialization for.
};
int main()
{
using U = A<A<A<double,3>,4>,5>;
U x;
constexpr size_t Depth = U::Depth(); // 3 + 4 + 5 = 12
std::cout << "Depth is " << Depth << std::endl;
A<double,Depth> y;
// Do stuff with x and y
return 0;
}
The static function A::Depth() returns the proper depth at compile time, which can then be used as a parameter to create other instances of A. It just seems like a messy hack to have to create both the DepthCalculator template and a specialization just for this purpose.
I know I can also create a specialization of A itself with a different definition of Depth(), but this is even more messy due to the number of methods in A, most of which depend on the template parameters. Another alternative is to inherit from A and then specialize the child classes, but this also seems overly complicated for something that seems should be simpler.
Are there any cleaner solutions using C++11?
Summary Edit
In the end, this is the solution I went with in my working project:
#include <array>
#include <iostream>
template<typename T,size_t N>
class A
{
std::array<T,N> arr;
template<typename U>
struct Get { };
template<size_t M>
struct Get<A<double,M>> { static constexpr size_t Depth() { return M; } };
template<typename U,size_t M>
struct Get<A<U,M>>
{ static constexpr size_t Depth() { return M + Get<U>::Depth(); } };
public:
static constexpr size_t GetDepth()
{
return Get<A<T,N>>::Depth();
}
// ...
// Too many methods in A to write a separate specialization for.
};
int main()
{
using U = A<A<A<double,3>,4>,5>;
U x;
constexpr size_t Depth = U::GetDepth(); // 3 + 4 + 5 = 12
std::cout << "Depth is " << Depth << std::endl;
A<double,Depth> y;
// Do stuff with x and y
return 0;
}
Nir Friedman made some good points about why GetDepth() should be an external function, however in this case there are other Get functions (not shown) which are appropriately member functions, and therefore it would make the most sense to have GetDepth() a member function too. I also borrowed Nir's idea of having the Depth() functions only call themselves, rather than GetDepth() which creates a bit less circular dependencies.
I chose skypjack's answer because it most directly provided what I had originally asked for.
You said:
I want to do this without having to create this extra helper template class DepthCalculator
So, maybe this one (minimal, working example) is fine for you:
#include<type_traits>
#include<cassert>
template<class T, std::size_t N>
struct S {
template<class U, std::size_t M>
static constexpr
typename std::enable_if<not std::is_arithmetic<U>::value, std::size_t>::type
calc() {
return M+U::calc();
}
template<typename U, std::size_t M>
static constexpr
typename std::enable_if<std::is_arithmetic<U>::value, std::size_t>::type
calc() {
return M;
}
static constexpr std::size_t calc() {
return calc<T, N>();
}
};
int main() {
using U = S<S<S<double,3>,4>,5>;
static_assert(U::calc() == 12, "oops");
constexpr std::size_t d = U::calc();
assert(d == 12);
}
I'm not sure I got exactly your problem.
Hoping this can help.
If you are with C++14, you can use also:
template<class U, std::size_t M>
static constexpr
std::enable_if_t<not std::is_arithmetic<U>::value, std::size_t>
If you are with C++17, it becomes:
template<class U, std::size_t M>
static constexpr
std::enable_if_t<not std::is_arithmetic_v<U>, std::size_t>
The same applies to the other sfinaed return type.
Option #1
Redefine your trait as follows:
#include <array>
#include <cstddef>
template <typename T>
struct DepthCalculator
{
static constexpr std::size_t Calculate()
{
return 0;
}
};
template <template <typename, std::size_t> class C, typename T, std::size_t N>
struct DepthCalculator<C<T,N>>
{
static constexpr size_t Calculate()
{
return N + DepthCalculator<T>::Calculate();
}
};
template <typename T, std::size_t N>
class A
{
public:
static constexpr size_t Depth()
{
return DepthCalculator<A>::Calculate();
}
private:
std::array<T,N> arr;
};
DEMO
Option #2
Change the trait into function overloads:
#include <array>
#include <cstddef>
namespace DepthCalculator
{
template <typename T> struct tag {};
template <template <typename, std::size_t> class C, typename T, std::size_t N>
static constexpr size_t Compute(tag<C<T,N>>)
{
return N + Compute(tag<T>{});
}
template <typename T>
static constexpr size_t Compute(tag<T>)
{
return 0;
}
}
template <typename T, std::size_t N>
class A
{
public:
static constexpr std::size_t Depth()
{
return Compute(DepthCalculator::tag<A>{});
}
private:
std::array<T,N> arr;
};
DEMO 2
You can do this wholly non-intrusively, which I think is advantageous:
template <class T>
struct Depth
{
constexpr static std::size_t Calculate()
{
return 0;
}
};
template <class T, std::size_t N>
struct Depth<A<T, N>>
{
constexpr static std::size_t Calculate()
{
return N + Depth<T>::Calculate();
}
};
Usage:
using U = A<A<A<double,3>,4>,5>;
constexpr size_t depth = Depth<U>::Calculate(); // 3 + 4 + 5 = 12
I realize your original question was how to do this without the extra "helper template", which my solution still has. But on the flip side, it's moved the functionality completely out of A itself, so its not really a helper template any more, it's just a template. This is pretty short, doesn't have any template template parameters unlike Piotr's solutions, is easy to extend with other classes, etc.