問(wèn)題描述
這段代碼有什么問(wèn)題?
#include <map>
template<typename T>
struct TMap
{
typedef std::map<T, T> Type;
};
template<typename T>
T test(typename TMap <T>::Type &tmap_) { return 0.0; }
int _tmain(int argc, _TCHAR* argv[])
{
TMap<double>::Type tmap;
tmap[1.1] = 5.2;
double d = test(tmap); //Error: could not deduce template argument for T
return 0;
}
推薦答案
那是不可推論的上下文.這就是編譯器無(wú)法推導(dǎo)出模板參數(shù)的原因.
That is non-deducible context. That is why the template argument cannot be deduced by the compiler.
試想一下,如果你有專門(mén)的 TMap
如下:
Just imagine if you might have specialized TMap
as follows:
template <>
struct TMap<SomeType>
{
typedef std::map <double, double> Type;
};
如果 TMap
是 std::map
,編譯器將如何推斷類型 SomeType
代碼>?這不可以.不能保證您在std::map
中使用的type也是type<TMap
中的/em>.編譯器不能做出這種危險(xiǎn)的假設(shè).無(wú)論如何,type 參數(shù)之間可能沒(méi)有任何關(guān)系.
How would the compiler deduce the type SomeType
, given that TMap<SomeType>::Type
is std::map<double, double>
? It cannot. It's not guaranteed that the type which you use in std::map
is also the type in TMap
. The compiler cannot make this dangerous assumption. There may not any relation between the type arguments, whatsoever.
此外,您可能還定義了 TMap
的另一個(gè)特化:
Also, you might have another specialization of TMap
defined as:
template <>
struct TMap<OtherType>
{
typedef std::map <double, double> Type;
};
這讓情況變得更糟.現(xiàn)在您擁有以下內(nèi)容:
This makes the situation even worse. Now you've the following:
TMap
=::Type std::map
.TMap
=::Type std::map
.
TMap<SomeType>::Type
=std::map<double, double>
.TMap<OtherType>::Type
=std::map<double, double>
.
現(xiàn)在問(wèn)問(wèn)自己:給定TMap
是std::map
,編譯器如何知道T
是 SomeType
還是 OtherType
?它甚至不知道有多少個(gè)這樣的選擇,它自己也不知道選擇...
Now ask yourself: given TMap<T>::Type
is std::map<double, double>
, how would the compiler know whether T
is SomeType
or OtherType
? It cannot even know how many such choices it has, neither can it know the choices themselves...
我只是為了思想實(shí)驗(yàn)而問(wèn)你(假設(shè)它可以知道完整的選擇集).
I'm just asking you for the sake of thought-experiment (assuming it can know the complete set of choices).
這篇關(guān)于當(dāng)模板參數(shù)用作另一個(gè)模板的模板參數(shù)時(shí),為什么不能推導(dǎo)出模板參數(shù)?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!