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

not getting expected ambiguity on template specialization and overloading c++

考虑

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

主要是

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

这个输出

2.2
overloading

我的问题是为什么它甚至可以编译? 实际上,foo 被定义为 void foo(int).

的两次

1) 为什么会通过?

2) 为什么编译器选择重载的?

谢谢

1)因为这里没有问题。有模板函数、函数模板特化和重载。您可以像这样调用模板特化:

wow.foo<int>(3);

2) 如果编译器可以使用 arg 调用此函数,则重载比模板特化更匹配。

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

F1 is not a function template specialization and F2 is a function template specialization