繁体   English   中英

接受任何大小的 char 的 std::array 作为非类型模板参数

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

这可能是一个奇怪的用例,但我试图破解字符串文字不能用作 arguments 到使用std::array<char, N>作为非模板类型参数的模板的事实。

这可行,但有一个极端的限制,即所有字符串必须具有相同的长度(我可以使用MAX_STR_LEN=100或其他任何东西,并使所有 arrays 大小,但感觉很难看......)。

有没有办法让这段代码工作,以便可以接受不同大小的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;;
        }
    });

}

当然,为什么不使用 requires requires 子句呢?

template <typename Type, auto val_val>
    requires requires { { val_val.data() } -> std::same_as<char const*>; }
struct TypeToValues
{
    // ...

例子

您还可以编写一个仅专门满足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
{
    // ...

但这感觉过于严格。 您将来会希望接受 static 字符串类型。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM