【问题标题】:Receive variadic sized raw arrays of the same type in a C++ template function在 C++ 模板函数中接收相同类型的可变参数大小的原始数组
【发布时间】:2021-11-26 10:25:01
【问题描述】:

我想实现如下逻辑,不知道能不能实现:

#include <stddef.h>
#include <array>

template<size_t SIZE>
constexpr std::array<const char*, 1> fun(const char (&name)[SIZE])
{
    return {name};
}

template<size_t SIZE_1, size_t SIZE_2>
constexpr std::array<const char*, 2> fun(const char (&name1)[SIZE_1], const char (&name2)[SIZE_2])
{
    return {name1, name2};
}

// I would like to do something like this:
template<size_t... SIZES>
constexpr std::array<const char*, sizeof...(SIZES)> fun(const char (&/*???*/)[SIZES]/*...*/)
{
    //???
}

int main()
{
    static constexpr auto fun1 = fun("aaa");
    static constexpr auto fun2 = fun("aaa", "bbb");
    //static constexpr auto funN = fun("aaa", "bbb", "ccc");
}

将参数作为原始数组获取以对它们进行额外的编译时魔法非常重要。

【问题讨论】:

    标签: c++ templates compile-time


    【解决方案1】:

    使用类型别名知道将... 放在哪里会简单得多

    template<std::size_t N>
    using chars = const char (&)[N];
    
    template<std::size_t... SIZES>
    constexpr std::array<const char*, sizeof...(SIZES)> fun(chars<SIZES>... names)
    {
        return { names... };
    }
    

    查看coliru

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-02
      • 2011-12-14
      • 2013-07-21
      • 1970-01-01
      • 2018-03-31
      • 1970-01-01
      • 2012-07-10
      相关资源
      最近更新 更多