Joe
Joe

Reputation: 381

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));

Upvotes: 3

Views: 124

Answers (2)

vsoftco
vsoftco

Reputation: 56547

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

Upvotes: 6

max66
max66

Reputation: 66200

The best I can imagine is add a 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 work only for some DTypes; by example, if DType is fixed to void

fun<std::string, void>(static_cast<std::string>(s));

you get a compilation error.

Upvotes: 0

Related Questions