当模板参数用作另一个模板的模板参数时,为什么不能推导出模板参数?

Why can#39;t the template argument be deduced when it is used as template parameter to another template?(当模板参数用作另一个模板的模板参数时,为什么不能推导出模板参数?)
本文介绍了当模板参数用作另一个模板的模板参数时,为什么不能推导出模板参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

这段代码有什么问题?

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

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Algorithm to convert RGB to HSV and HSV to RGB in range 0-255 for both(将 RGB 转换为 HSV 并将 HSV 转换为 RGB 的算法,范围为 0-255)
How to convert an enum type variable to a string?(如何将枚举类型变量转换为字符串?)
When to use inline function and when not to use it?(什么时候使用内联函数,什么时候不使用?)
Examples of good gotos in C or C++(C 或 C++ 中好的 goto 示例)
Significance of ios_base::sync_with_stdio(false); cin.tie(NULL);(ios_base::sync_with_stdio(false) 的意义;cin.tie(NULL);)
Is TCHAR still relevant?(TCHAR 仍然相关吗?)