简体   繁体   中英

How to call a generic function with typename and non-typename template arguments?

I need to implement a function with the following prototype:

template<typename Iterator, size_t NBITS>
void radix_sort(Iterator first, Iterator last) {

// some code

}

If there wasn't the NBITS template argument, it would figure out by itself what Iterator is and I would call the function without the <> . Here I would like to specify the value of NBITS when calling the function.

I'm not sure if I need to provide the type of Iterator too in that case, and how I would do that.

Can I call it in a way that it can figure out Iterator by itself while I'm providing the value for NBITS ?

NOTE: I'm not allowed to edit the prototype

With the current function template, you'll need to provide the Iterator template parameter explicitly if you also want to specify the size_t argument. You can do this by passing in the type of the first argument to the function

std::vector<int> v;
radix_sort<decltype(v.begin()), 42>(v.begin(), v.end());

To avoid having to specify Iterator at the call site, you can add another overload that swaps the template parameters, and calls your overload with the deduced type

template<std::size_t NBITS, typename Iterator>
void radix_sort(Iterator first, Iterator last) 
{
    radix_sort<Iterator, NBITS>(first, last);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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