简体   繁体   English

在模板专业化和重载C ++上没有得到预期的歧义

[英]not getting expected ambiguity on template specialization and overloading c++

Consider 考虑

Class Wow{
    public:
        //main metod
        template<typename T>
        void foo(T t){
            cout << t << endl;
        }

        template<>
        void foo<int>(int t){
            cout << "specialization" << endl;
        }

        void foo(int t){
            cout << "overloading" << endl;
        }
}

and the main is 主要是

Wow wow;
wow.foo(2.2);
wow.foo(1);

this outputs 这个输出

2.2
overloading

My question is why does that even compile? 我的问题是为什么还要编译? practically, foo is defined twice as void foo(int) . 实际上, foo被两次定义为void foo(int)

1) why does this pass? 1)为什么会通过?

2) why does the compiler choose the overloading one? 2)为什么编译器选择重载?

Thanks 谢谢

1) Because there is no problem here. 1)因为这里没有问题。 There is template function, function template specialization and overloading. 有模板功能,功能模板专门化和重载。 You can call template specialization like this: 您可以这样调用模板专门化:

wow.foo<int>(3);

2) Overload has better match, than template specialization, if compiler can call this function with arg. 2)如果编译器可以使用arg调用此函数,则重载比模板专业化更好。

n4926 13.3.3/1.7 n4926 13.3.3 / 1.7

Given these definitions, a viable function F1 is defined to be a better function than another viable function F2 if for all arguments i, ICSi(F1) is not a worse conversion sequence than ICSi(F2) , and then 给定这些定义,如果对于所有参数i,ICSi(F1)的转换顺序都不比ICSi(F2)的转换顺序差,则将可行函数F1定义为比另一个可行函数F2更好的函数,然后

F1 is not a function template specialization and F2 is a function template specialization F1不是功能模板专业化,而F2不是功能模板专业化

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

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