2017-10-05 70 views
3

我試圖做一個SFINAE激勵例如,當 我注意到,你不需要那麼以下:爲什麼我不需要在這裏SFINAE

#include <iostream> 

using namespace std; 

template<typename T> 
struct Foo 
{ 
    void add(int count, const T& val) // add "count" number of val's 
    { 
     cout << "count, val" << endl; 
    } 

    template<typename It> 
    void add(It beg, It end) // add items [beg,end) 
    { 
     cout << "beg, end" << endl; 
    } 
}; 

int main() 
{ 
    int a=1; 
    int xx[] = {1,2,3}; 
    Foo<int> foo; 
    foo.add(xx, xx+3); 
    foo.add(2, a); 
} 

這將編譯,運行,並打印:

求,最終
計數,VAL

try it here

我不明白爲什麼第二次打電話給add並不明確。

回答

10

基本上:

  • 兩種過載是活的。
  • 兩者都沒有轉換/促銷匹配。
  • add(int count, const T& val)作爲非模板是優選的。
+2

不知道非模板是首選。有用的信息。 – sp2danny

+0

@ sp2danny在這種情況下,您可能需要閱讀[重載解析規則](http://en.cppreference.com/w/cpp/language/overload_resolution)。 –