C ++,模板参数无法推导 [英] C++, template argument can not be deduced

查看:143
本文介绍了C ++,模板参数无法推导的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这段程式码有什么问题?

  #include< map& 

template< typename T>
struct TMap
{
typedef std :: map< T,T&类型;
};

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); //错误:无法推导出T
的模板参数return 0;
}


解决方案

。这就是为什么编译器无法推导出模板参数的原因。



想象一下,你可能有专门的 TMap

 模板<> 
struct TMap< SomeType>
{
typedef std :: map< double,double>类型;
};

编译器如何推导类型 SomeType ,因为 TMap< SomeType> :: Type std :: map< double,double> ?它不能。它不保证在 std :: map 中使用的类型 em> TMap 。编译器不能做这个危险的假设。



此外,您可能还有 TMap 参数的其他特殊化。 / code>定义为:

 模板< 
struct TMap< OtherType>
{
typedef std :: map< double,double>类型;
};

这使情况更糟。现在你有以下的:




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

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

    现在问问自己:给定 TMap< T> :: Type is std :: map< double,double> ,编译器如何知道 T SomeType 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, 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. Its 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 other 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).

    这篇关于C ++,模板参数无法推导的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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