当模板参数用作另一个模板的模板参数时,为什

时间:2022-11-19
本文介绍了当模板参数用作另一个模板的模板参数时,为什么不能推导出模板参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这段代码有什么问题?

#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;
}

推荐答案

那是不可推论的上下文.这就是编译器无法推导出模板参数的原因.

That is non-deducible context. That is why the template argument cannot be deduced by the compiler.

试想一下,如果你有专门的 TMap 如下:

Just imagine if you might have specialized TMap as follows:

template <>
struct TMap<SomeType>
{
    typedef std::map <double, double> Type;
};

如果 TMap::Typestd::map,编译器将如何推断类型 SomeType代码>?这不可以.不能保证您在std::map中使用的type也是type<TMap 中的/em>.编译器不能做出这种危险的假设.无论如何,type 参数之间可能没有任何关系.

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 的另一个特化:

Also, you might have another specialization of TMap defined as:

template <>
struct TMap<OtherType>
{
    typedef std::map <double, double> Type;
};

这让情况变得更糟.现在您拥有以下内容:

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>.

现在问问自己:给定TMap::Typestd::map,编译器如何知道TSomeType 还是 OtherType?它甚至不知道有多少个这样的选择,它自己也不知道选择...

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...

我只是为了思想实验而问你(假设它可以知道完整的选择集).

I'm just asking you for the sake of thought-experiment (assuming it can know the complete set of choices).

这篇关于当模板参数用作另一个模板的模板参数时,为什么不能推导出模板参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!