假设我有一个模板函数,例如:
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 所述。在评论中:“与类模板不同,函数模板的默认模板参数不需要位于尾随模板参数上。”
关于c++ - 指定默认模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44012357/