指定默认模板参数

Specify default template argument

本文关键字:参数 默认      更新时间:2023-10-16

>假设我有一个模板函数,如下所示:

template<typename T, typename DType=uint32_t>
void fun(T a) {
    //...
    // DType is used inside
}

如何指定DType的类型,但让编译器推导出T,如下所示:

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

当你写它时,你不能。最好的办法是交换类型,让编译器推断出T的类型,比如

template<typename DType=uint32_t, typename T>
void fun(T a) {
    //...
    // DType is used inside
}

编译器将相应地推断T的类型。

#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
}

正如 @T.C. 在评论中提到的:">与类模板不同,函数模板的默认模板参数不需要位于尾随模板参数上。

住在科里鲁

我能想象的最好的就是添加一个DType未使用的参数

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

显然,这只适用于某些DTypes;例如,如果DType固定为void

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

您收到编译错误。