Assume I have a template function like:
template<typename T, typename DType=uint32_t>
void fun(T a) {
//...
// DType is used inside
}
How can I specify the type of DType, but let T be deduced by the compiler, something like:
fun<DType=int32_t>(static_cast<std::string>(s));
As you wrote it you cannot. Your best bet is to interchange the types and let the compiler deduce the type for T, like
template<typename DType=uint32_t, typename T>
void fun(T a) {
//...
// DType is used inside
}
The compiler will deduce the type of T accordingly.
Example
#include <iostream>
template<typename DType = uint32_t, typename T>
void fun(T a) {
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
int main()
{
fun<char>(42); // T is deduced as int, DType as char
}
As mentioned by @T.C. in the comments: "There's no requirement that default template arguments for function templates be on trailing template parameters, unlike class templates."
Live on Coliru
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With