2017-10-05 59 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)。 –