Deduce template argument for size of initializer list

前端 未结 2 1341
既然无缘
既然无缘 2021-01-21 03:14

I have the following (not compilable) code:

template< size_t N >
void foo( std::array )
{
  // Code, where \"N\" is used.
}

int main()
{
  f         


        
相关标签:
2条回答
  • 2021-01-21 04:00

    Thanks to core issue 1591, you can use

    template <std::size_t N>
    void foo( int const (&arr)[N] )
    {
      // Code, where "N" is used.
    }
    
    foo({1, 2, 3});
    
    0 讨论(0)
  • 2021-01-21 04:04

    If using an initializer list is not a must, you can use variadic template parameter packs:

    template<size_t S>
    void foo_impl(array<int, S> const&)
    {
        cout << __PRETTY_FUNCTION__ << endl;
    }
    
    template<typename... Vals>
    auto foo(Vals&&... vals) {
        foo_impl<sizeof...(vals)>({ std::forward<Vals>(vals)... });
    }
    

    you'd call it as follows:

    foo(1,2,3,4,5);
    

    This defers common type checks until the initialization point of std::array (unless you add some admittedly ugly asserts), so you probably should prefer Columbo's answer.

    0 讨论(0)
提交回复
热议问题