当将模板参数用作另一个模板的模板参数时,为什么不能推导它呢? [英] Why can't the template argument be deduced when it is used as template parameter to another template?

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

问题描述

此代码有什么问题?

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

解决方案

这是不可推论的上下文.这就是为什么模板参数不能由编译器推论的原因.

试想一下,您是否可以按照以下方式专门使用TMap:

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

TMap<SomeType>::Typestd::map<double, double>的情况下,编译器将如何推断类型SomeType?这不可以. 不能保证在std::map中使用的类型TMap中也是也是 类型.编译器无法做出这个危险的假设. type 参数之间可能没有任何关系.

此外,您可能还定义了TMap的另一种专业化:

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

这使情况更加糟糕.现在您有了以下内容:

  • TMap<SomeType>::Type = std::map<double, double>.
  • TMap<OtherType>::Type = std::map<double, double>.

现在问问自己:给定TMap<T>::Typestd::map<double, double>,编译器将如何知道TSomeType还是OtherType?它甚至不知道它有多少选择,他们自己也不知道选择.

我只是想为您进行思想实验(假设它可以知道全套选择).

What is wrong in this code?

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

Just imagine if you might have specialized TMap as follows:

template <>
struct TMap<SomeType>
{
    typedef std::map <double, double> 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.

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<SomeType>::Type = std::map<double, double>.
  • TMap<OtherType>::Type = std::map<double, double>.

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆