2012-10-02 58 views
2

下面的代碼失敗,英特爾C++ 2013年爲什麼這些函數模板都不匹配實例?

#include <type_traits> 
#include <iostream> 


template < 
    typename T, 
    typename std::enable_if<std::is_integral<T>::value>::type 
> 
void myfunc(T a) 
{ 
    std::cout << a << std::endl; 
} 

template < 
    typename T, 
    typename std::enable_if<!std::is_integral<T>::value>::type 
> 
void myfunc(T a) 
{ 
    std::cout << a << std::endl; 
} 




int main() 
{ 
    double a; 
    int b; 
    myfunc(a); 
    myfunc(b); 

    return 0; 

} 

以下是錯誤輸出編譯:

ConsoleApplication1.cpp(33): error : no instance of overloaded function "myfunc" matches the argument list 
1>    argument types are: (double) 
1>  myfunc(a); 
1> ^
1> 
1>ConsoleApplication1.cpp(34): error : no instance of overloaded function "myfunc" matches the argument list 
1>    argument types are: (int) 
1>  myfunc(b); 
1> ^
1> 

我要去哪裏錯了?

+1

'std :: cout << T'?你的意思是'a'嗎? – kennytm

+0

是的,謝謝。糾正。 –

+0

您不能擁有void類型的模板非類型參數。告訴enable_if給你一個類型int和ptovide默認值 –

回答

3

在函數中使用enable_if的常用方法是將其固定在返回類型中。

template <typename T> 
typename std::enable_if<std::is_integral<T>::value>::type myfunc(T a) { 
    std::cout << a << " (integral)" << std::endl; 
} 

template <typename T> 
typename std::enable_if<!std::is_integral<T>::value>::type myfunc(T a) { 
    std::cout << a << " (non-integral)" << std::endl; 
} 

爲了您的變種,正確的方法是:

template <typename T, 
      typename = typename std::enable_if<std::is_integral<T>::value>::type> 
void myfunc(T a) { 
    std::cout << a << " (integral)" << std::endl; 
} 

...的 「enable_if」 是默認模板參數。它不適用於你的情況,因爲該函數沒有超載。

+0

謝謝,我知道它更頻繁使用,但我使用的變體(或至少它的一個正確版本!)也是可以接受的,我想在這種情況下使用void函數。 –

+0

@JoshGreifer'enable_if'省略的第二個參數默認爲'void'。這個答案中的myfunc不需要返回任何值,返回類型是'void'。 – hvd

+0

好吧我想我明白了 - 所以如果我想讓myfuncs返回int,我可以使用'std :: enable_if <!std :: is_integral :: value,int> :: type'? –

相關問題