简体   繁体   English

VC6和VS2008之间的模板功能行为

[英]template function behavor between VC6 and VS2008

I have simple code about template function for Visual C++ 6.0 and Visual Studio 2008. 我有关于Visual C ++ 6.0和Visual Studio 2008模板功能的简单代码。

#include <stdio.h>
#include <vector>

template<typename T>
void function(const std::vector<T> &vec)
{
    printf("vector version\n");
}

template<typename T>
void function(T val)
{
    printf("value version\n");
}

int main()
{
    std::vector<int> vec;
    function(vec);

    return 0;
}

I tried for each environment, and finally get 我尝试了每种环境,最后得到了
at VC6, function of value version, and 在VC6中, 版本的功能,以及
at VS2008, function of vector version. 在VS2008中, 矢量版本的功能。

I have 2 questions. 我有两个问题。

  1. I have recognized priority of overloaded function call as following, 我已经认识到重载函数调用的优先级如下,
    a) specialized function (without implicit type convert) a)特殊功能(无隐式类型转换)
    b) template function (without implicit type convert) b)模板函数(无隐式类型转换)
    c) specialized function, with implicit type convert c)特殊功能,具有隐式类型转换
    d) template function, with implicit type convert d)模板函数,具有隐式类型转换

    with this rule, the above results seems that 用这个规则,上面的结果似乎是
    at VC6, b) is accepted (with <T> = std::vector<int>) 在VC6中,b)被接受(<T> = std :: vector <int>)
    at VS2008, b) is ignored(?) and d) is accepted(?) (with <T> = int) 在VS2008中,b)被忽略(?),而d)被接受(?)(其中<T> = int)

    This means that VC6 is valid and VS2008 is wrong. 这意味着VC6有效,而VS2008错误。
    Is not my guess correct? 我的猜测不正确吗?

  2. Although, I wish vector version is called for both VC6 and VS2008. 虽然,我希望VC6和VS2008都需要向量版本。
    Can I do it? 我可以做吗?

Regards. 问候。

Actually VC6 is wrong; 其实VC6是错误的; MS had limited support for the C++99 standard (which is when templates were standardized) in VC6 and had better support in VS2005 and up. MS在VC6中对C ++ 99标准(即模板标准化)的支持有限,而在VS2005及更高版本中具有更好的支持。

Calling function(vec) calls 调用function(vec)调用

template<typename T>
void function(const std::template vector<T>& vec)

with T as an int type because the template was deduced from the vector template type (the same as calling function<int>(vec) ). 使用T作为int类型,因为该模板是从矢量模板类型推导的(与调用function<int>(vec) )。 If you called function(&vec) then the value function will be called since you're passing in a reference, which gets deduced to function<std::vector<int>>(vec) . 如果您调用function(&vec)则将在您传递引用时调用值函数,该引用推导为function<std::vector<int>>(vec)

If you want it to always call the proper function, then you'll need to be explicit, so you'd need to call it as such: 如果希望它总是调用适当的函数,则需要明确,因此需要这样调用:

function< std::vector<int> >(vec)

Which will deduce to the vector version. 这将推导为矢量版本。 Note the space between the > , this is to avoid the compiler thinking you meant the stream operator >> . 注意>之间的空格,这是为了避免编译器认为您的意思是流运算符>>

Hope that helps. 希望能有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM