具有另一个具有默认值的模板参数的模板推导

时间:2018-07-30 16:13:25

标签: c++ templates template-deduction

下面的代码将无法编译,因为当我要指定import { Component, Inject } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.css'] }) export class HomeComponent { public news: News[]; public headline: News; constructor(private http: HttpClient, @Inject('BASE_URL') private baseUrl: string) { } ngOnInit() { var headurl = this.baseUrl + "api/News/Headline?country=us&category=business"; this.fetchData(headurl, function (res) { //this code does not work this.headline = res; }); } fetchData(url, callback) { this.http.get<News>(url).subscribe(result => { callback(result); //this code works! this.headline = result; }, error => console.error(error)); } } interface News { SourceId: string; SourceName: string; Author: string; Title: string; Description: string; Url: string; UrlToImage: string; PublishedAt: string; } 时,将禁用ParamA的类型推断,因此我也必须明确地指定它们。 / p>

B

Coliru

是否有可能通过扣除#include <iostream> template<typename A, typename B> struct L { }; template<typename A, typename B, unsigned Param = 0> void fn(L<A, B> l_) {} int main() { L<int, float> l; fn<3>(l); } A而获得两全其美,但仍然能够提供B,如果保留该值,该值将为默认值出来吗?

1 个答案:

答案 0 :(得分:4)

是的,当然,您只需要将Param参数放在首位(以便您可以明确指定它):

template<unsigned Param = 0, typename A, typename B>
void fn(L<A, B> l_) {}

请注意,即使AB没有默认参数也可以使用,因为它们可以推导。