指定默认模板参数
Specify default template argument
>假设我有一个模板函数,如下所示:
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));
您收到编译错误。
相关文章:
- 使函数参数默认为周围范围
- 如何将值传递给其参数(默认参数)
- 当“std::make_index_sequence”和“std::index_sequence”用于模板参数默认类型时
- C ,构造器中允许的参考参数默认值
- 哪些规则控制参数默认赋值?
- 错误:上一个规范后给出的参数默认参数
- 是否可以设计一个包含模板参数默认值的类
- 构造函数中参数C++默认值
- 如何设置依赖于其他参数的参数默认值
- C++模板参数默认函数实现
- QInput对话框参数默认值
- g++4.8.2上列表方法参数默认初始化时出错
- 在函数定义中指定参数默认值会导致错误 C2143:语法错误:'='之前缺少')'
- 函数模板:将第一个模板参数默认为第二个
- 模板模板参数默认可以引用其他模板类型的参数
- 参数默认为先例参数的值
- 如何修改一个类,使它只有一个成员函数,所有参数默认
- 内置类型的模板参数默认值
- 是否可以使用构造函数或对象作为其他类方法的参数默认值?
- 模板参数默认为更高版本