[英]Or statement in C++ template programming
我有一個大致如此構成的程序。
#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)
typename std::enable_if<std::is_same<T, Input>::value || std::is_same<T, Output>::value>>::type operator&(T& t, C& c)
。 C ++模板是否提供此類“或”語句?
答案非常簡單-使用||
-正是您所提出的問題。 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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.