Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specify default template argument

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));
like image 450
Joe Avatar asked Jun 16 '26 15:06

Joe


1 Answers

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

like image 165
vsoftco Avatar answered Jun 19 '26 04:06

vsoftco