Specify default template argument
As you wrote, you cannot. Your best bet is to swap types and let the compiler infer the type for T
e.g.
template<typename DType=uint32_t, typename T>
void fun(T a) {
//...
// DType is used inside
}
The compiler will determine the type accordingly T
.
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 @TC mentioned in the comments: "There is no requirement for default template arguments for function templates to be on final template parameters as opposed to class templates."
source to share
The best I can imagine is to add an DType
unused argument
#include <iostream>
template<typename T, typename DType = uint32_t>
void fun(T a, DType = 0) {
//...
// DType is used inside
}
int main ()
{
char s[] = "abc";
fun(static_cast<std::string>(s));
fun(static_cast<std::string>(s), int32_t{0});
}
Obviously this only works for some DTypes
; for example, if DType
fixed onvoid
fun<std::string, void>(static_cast<std::string>(s));
compilation error appears.
source to share