![](/img/trans.png)
[英]How to deduce template return type with another template parameter with explicit specialization?
[英]How to deduce template parameter in explicit specialization of function template?
考慮以下案例:
#include <iostream>
template <class T> void f(T) { std::cout << "#1\n"; } // #1
template <> void f(const int) { std::cout << "#2\n"; } // #2
int main() {
f<const int>(1); // call #1
f<int>(1); // call #2
return 0;
}
似乎#2是f<int>(const int)
而不是f<const int>(const int)
。 這里發生了什么? 我的第一個想法是在函數類型轉換中丟棄頂級const
,因此#2的類型是void(int)
,這導致f<int>(const int)
。 但我不確定。
為什么C ++允許這樣的語法? 我的意思是因為我們不能部分地專門化函數模板,如果我們想要明確地專門化一個,我們就會知道模板參數值。 那么為什么C ++不僅僅強制程序員在專門化模板函數時顯式提供模板參數值? (即我們必須在template <> void f<int>(const int) { }
編寫#1的專門化template <> void f<int>(const int) { }
或template <> void f<int const>(const int) { }
)它是否有特殊用途,除了編碼方便嗎?
void f(const int p)
暫且不考慮模板的問題,這里的const
部分沒有指定f()
參數的類型。 這里指定的所有const
都是函數f()
中的p
是const
。 f()
的參數類型是int
。
template <> void f(const int)
當編譯器試圖推斷出特化的類型時,它推斷出因為函數參數的類型是int
,所以它必須是f<int>
。
無法以這種方式真正做出演繹工作。 你必須明確,如果這是你想要做的:
template <> void f<const int>(const int) { std::cout << "#2\n"; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.