2014-06-13 28 views
1

我有一個類似這樣的程序。或C++模板編程語句

#include <iostream> 
#include <type_traits> 

class Output 
{ 
public: 
    template <typename T> 
    Output& operator&(T const& t) 
    { 
     std::cout << t << std::endl; 

     return *this; 
    } 
}; 

class Input 
{ 
public: 
    template <typename T> 
    Input& operator&(T& t) 
    { 
     std::cin >> t; 

     return *this; 
    } 
}; 

class C 
{ 
    public: 
     int num1, num2; 
}; 

template <typename T> 
typename std::enable_if<std::is_same<T, Input>::value>::type operator&(T& t, C& c) 
{ 
    t & c.num1 & c.num2; 
} 

template <typename T> 
typename std::enable_if<std::is_same<T, Output>::value>::type operator&(T& t, C& c) 
{ 
    t & c.num1 & c.num2; 
} 

int main() 
{ 
    Output o; 
    Input i; 
    C c; 

    i & c; 
    o & c; 

    return 0; 
} 

它的偉大工程,但我會非常喜歡的功能typename std::enable_if<std::is_same<T, Input>::value>::type operator&(T& t, C& c)typename std::enable_if<std::is_same<T, Output>::value>::type operator&(T& t, C& c)結合起來。所以我正在尋找類似typename std::enable_if<std::is_same<T, Input>::value || std::is_same<T, Output>::value>>::type operator&(T& t, C& c)的東西。 C++模板是否提供這樣的'或'語句?

+1

你已經回答了你自己的問題---你可以用''||完全按照你所想。 –

回答

6

答案非常簡單 - 使用|| - 正是你的問題。 enable_if的第一個參數是bool,因此您可以使用產生編譯時布爾值的任何表達式組合。

template <typename T> 
typename std::enable_if< 
    std::is_same<T, Input>::value || 
    std::is_same<T, Output>::value 
>::type operator&(T& t, C& c) 
{ 
    t & c.num1 & c.num2; 
} 

Live demo

+0

嗯,哎呀。我以爲我嘗試過。我可能輸入了錯誤的內容。謝謝。 – Scintillo