指定默认模板参数

时间:2017-05-16 22:03:49

标签: 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));

2 个答案:

答案 0 :(得分:6)

正如你所写,你做不到。最好的办法是交换类型,让编译器推导出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

答案 1 :(得分:0)

我能想象的最好的是添加export const myRouters: Array<any> = [ { path: "", redirectTo: "something", pathMatch: "full", }, { name: "somepath", path: "somepath", component: MyComponent, canDeactivate: [CanDeactivateTeam], ... } } 未使用的参数

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

您收到编译错误。