【问题标题】:How can I push template args to an Array如何将模板参数推送到数组
【发布时间】:2021-12-05 02:37:38
【问题描述】:

如何将模板参数推送到数组?

我想让这个函数在下面返回 来自模板 args 的整数值数组

template <int... args>
int* data(... args)
{
    int* m_data = // push template args to array
}

【问题讨论】:

  • 您是否一心想要使用C 样式数组? std::vector 怎么样?
  • 我正在尝试创建类似 std::vector 的东西,这是用于类的构造函数
  • 您是否在data 函数中动态创建数组?或者,它是否在调用data 函数之前已经创建?
  • data(... args) 不会编译。目前尚不清楚您是要将值作为模板参数还是作为“普通”函数参数传递。 data 应该怎么称呼?
  • 这只是一个例子,我想知道如何将模板参数推送到数组

标签: c++ c++11 visual-c++ c++17


【解决方案1】:

您可以使用以下内容动态分配array 并在构造期间填充数组的元素。

动态数组

template<typename ...Args>
static int* data( Args&& ...args ) 
{
    constexpr auto size = sizeof...( Args );
    int* a1{ new int[ size ]{ std::forward<Args>( args )... } };
    return a1;
}

int main( ) 
{
    int* ptr{ data( 1, 2, 3, 4, 5, 6 ) };
    delete[ ] ptr;
}

静态数组

template<typename ...Args>
static int* data( Args&& ...args ) 
{
    constexpr auto size = sizeof...( Args );
    static int a1[ size ]{ std::forward<Args>( args )... };
    return a1;
}

int main( ) 
{
    int* ptr{ data( 1, 2, 3, 4, 5, 6 ) };
    
}

构造后填充数组

template<typename ...Args>
static int* data( Args&& ...args ) 
{
    constexpr auto size = sizeof...( Args );

    // Use can also use a static array here instead.
    int* a1{ new int[ size ] };

    std::size_t count{ 0 };
    for ( auto value : { std::forward<Args>( args )... } )
    {
        a1[ count++ ] = value;
    }

    return a1;
}

int main( ) 
{
    int* ptr{ data( 1, 2, 3, 4, 5, 6 ) };
    delete[ ] ptr;
}

断言所有值都是 int 类型

template<typename ...Args>
static int* data( Args&& ...args ) 
{
    static_assert( std::conjunction_v<std::is_same<int, Args>...>, 
        "All args must be of type 'int'" );

    constexpr auto size = sizeof...( Args );
    int* a1{ new int[ size ]{ std::forward<Args>( args )... } };
    return a1;
}

int main( ) 
{
    int* ptr{ data( 1, 2, 3, 4, 5, 6, 7.0 ) };
    delete[ ] ptr;
}

【讨论】:

  • 不需要动态分配。只需创建一个静态数组并返回它。
  • @0x499602D2 我不确定他的用例是什么,这就是我选择动态数组的原因。我会同时显示。
  • 如果我想用特定类型(例如 int)制作 args 怎么办
  • @SobhyRzk 编辑了答案以显示如何使用static_assert 来验证所有值的类型为int
  • @SobhyRzk 如果我的回答对你有帮助,请务必采纳。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-27
  • 1970-01-01
  • 2021-09-15
相关资源
最近更新 更多