Specify default template argument

Suppose 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 DType

, but let it T

be deduced by the compiler, something like:

fun<DType=int32_t>(static_cast<std::string>(s));

      

+3


source to share


2 answers


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."

Live on Coliru

+6


source


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.

0


source







All Articles