c++ - 指定默认模板参数

标签 c++ c++11 templates

假设我有一个模板函数,例如:

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 所述。在评论中:“与类模板不同,函数模板的默认模板参数不需要位于尾随模板参数上。”

Live on Coliru

关于c++ - 指定默认模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44012357/

相关文章:

c++ - 函数模板作为成员 - GCC 与 CLANG

templates - 什么语言或框架通常使用诸如 "&lt;!--ls:begin[stylesheet]-->"之类的标签

php - Smarty 可以只读取一个 block 而不是模板吗?

c++ - 如何实现QProgressDialog?

c++ - 编译器生成的 move 构造函数的行为是什么?

c++ - 我应该停止使用术语 C/C++ 吗?

c++ - 为什么 C++ 编译器找不到运算符 <<

c++ - 无需创建 T 元素的 lower_bound 功能

c++ - 在 C++ 元编程中是否全部使用模板?

c++ - 如何在 visual studio 2015 中显示 "unimplemented pure virtual"?