So this answer demonstrates how I can use a function in the return type to force Substitution Failure is not an Error (SFINAE).
Is there a way that I can use this and have a different return type from the function?
So a arguments line this to overload
will trigger the SFINAE:
overload {
[&](auto& value) -> decltype(void(value.bar())) { value.bar(); } ,
[](fallback_t) { cout << "fallback\n"; }
}
But lets say that I need a different return type, how can I still trigger SFINAE? For example I'd like to do something like this:
overload {
[&](auto& value) -> decltype(void(value.bar()), float) { value.bar(); return 1.0F; } ,
[](fallback_t) { cout << "fallback\n"; return 13.0F; }
}
This is the minimal, complete, verifiable example. It's a lot to read but if you don't want to go check out the link, this is the code that's involved before I try to add the return type:
struct one {
void foo(const int);
void bar();
};
struct two {
void foo(const int);
};
struct three {
void foo(const int);
void bar();
};
template<class... Ts> struct overload : Ts... { using Ts::operator()...; };
template<class... Ts> overload(Ts...) -> overload<Ts...>;
struct fallback_t { template<class T> fallback_t(T&&) {} };
struct owner {
map<int, one> ones;
map<int, two> twos;
map<int, three> threes;
template <typename T, typename Func>
void callFunc(T& param, const Func& func) {
func(param);
}
template <typename T>
void findObject(int key, const T& func) {
if(ones.count(key) != 0U) {
callFunc(ones[key], func);
} else if(twos.count(key) != 0U) {
callFunc(twos[key], func);
} else {
callFunc(threes[key], func);
}
}
void foo(const int key, const int param) { findObject(key, [&](auto& value) { value.foo(param); } ); }
void bar(const int key) {
findObject(key, overload {
[&](auto& value) -> decltype(void(value.bar())) { value.bar(); } ,
[](fallback_t) { cout << "fallback\n"; }
} );
}
};
int main() {
owner myOwner;
myOwner.ones.insert(make_pair(0, one()));
myOwner.twos.insert(make_pair(1, two()));
myOwner.threes.insert(make_pair(2, three()));
myOwner.foo(2, 1);
cout << myOwner.bar(1) << endl;
cout << myOwner.bar(2) << endl;
cout << myOwner.foo(0, 10) << endl;
}