最新のC++では、ラムダを使用して任意の演算子を渡すことができます。
更新1:提案されたソリューションは@HolyBlackCatによって提案された小さな改善を導入します
#include <iostream>
template<class T, class F> void reveal_or(T a, T b, F f)
{
// using as function(a, b) instead of expression a || b is the same thing
if ( f(a, b) )
std::cout << a << " is || " << b << std::endl;
else
std::cout << a << " is not || " << b << std::endl;
}
template<class T> void reveal_or(T a, T b)
{
// reuse the already defined ||
reveal_or(a, b, [](T t1, T t2) {return t1 || t2; });
}
||の場合、パラメータの受け渡し方法を気にしないでください。演算子が定義されています
int main ()
{
reveal_or('1', 'a');
return 0;
}
パラメータとして明示的に渡す。エキゾチックなナンセンスを含め、何でも渡すことができます
int main ()
{
//same as above:
reveal_or('1', 'a', [](char t1, char t2) { return t1 || t2; });
//opposite of above
reveal_or('1', 'a', [](char t1, char t2) { return !( t1 || t2; ) });
return 0;
}