[英]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.这可能是一个奇怪的用例,但我试图破解字符串文字不能用作 arguments 到使用
std::array<char, N>
作为非模板类型参数的模板的事实。
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...).这可行,但有一个极端的限制,即所有字符串必须具有相同的长度(我可以使用
MAX_STR_LEN=100
或其他任何东西,并使所有 arrays 大小,但感觉很难看......)。
Is there a way to make this code work so that different size std::array
s can be accepted as template parameter?有没有办法让这段代码工作,以便可以接受不同大小的
std::array
作为模板参数?
#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?当然,为什么不使用 requires requires 子句呢?
template <typename Type, auto val_val>
requires requires { { val_val.data() } -> std::same_as<char const*>; }
struct TypeToValues
{
// ...
You could also write a constraint that only specifically std::array<char, N>
satisfy:您还可以编写一个仅专门满足
std::array<char, N>
的约束:
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.
您将来会希望接受 static 字符串类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.