簡體   English   中英

是否可以在調用函數模板時僅指定一些模板參數並讓編譯器推斷其他參數

[英]Is it possible to specify only some template parameters when calling a function template and let the compiler deduce the others

考慮以下函數模板:

template <typename T1, typename T2>
void foo(T1 a, T2 b){// Do something.}

現在假設我希望T1int ,但T2由編譯器根據b的類型推導出。 類似foo<int,...>(1,b) 是否可以?

謝謝!

是的!

foo<int>(1, b);

但是在上面的那個例子中沒有任何好處。 如果您的第一個參數尚未推斷為int則差異是可見的:

foo<int>(3.2f, b);
//       ^^^^ Implicit conversion

Quentin 的回答最方便。

但是有其他方法可以解決這個問題,顯而易見地想出它。 由於強制特定模板類型會導致靜默轉換,有時只進行顯式轉換可能更明智。

double x = 1.1;
foo(static_cast<int>(x), boost::lexical_cast<int>(y));

經典示例是使用std::move僅轉換為 xvalue。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM