От: | Кодт | ||
Дата: | 25.08.14 09:44 | ||
Оценка: | 6 (1) |
Note: thanks to the semantics of , (the comma operator) you can chain multiple expressions in decltype and only the last actually decides the type. Handy to check multiple operations.
#include <iostream>
using namespace std;
struct Foo {};
int foo(int) { return 0; }
Foo foo(double) { return Foo(); }
// no foo(const char*)
struct Bar { Bar(bool) {} };
ostream& operator << (ostream& ost, Bar&& bar) { return ost << "BARR"; }
Bar operator , (Foo&&, bool) { return Bar(true); } // ВНЕЗАПНО!
// требование к then-ветке функции: чтобы была определена функция foo(T)
template<class T> auto test1(T&& t) -> decltype(foo(t), true) { return true; }
auto test1(...) -> bool { return false; }
template<class T> auto test2(T&& t) -> decltype(foo(t), void(0), true) { return true; }
auto test2(...) -> bool { return false; }
int main()
{
cout << boolalpha << test1(1) << " " << test1(1.) << " " << test1("") << endl; // true BARR false
cout << boolalpha << test2(1) << " " << test2(1.) << " " << test2("") << endl; // true true false
return 0;
}