Consider:
int convert_it(std::string& x) { return 5; } void takes_int_ref(int& i) { }
I want to write a function that exists only if convert_it can be applied, and the result is passed to takes_int_ref . That is, the body of the function:
template <typename A> void doit(A& a) { int i = convert_it(a); takes_int_ref(i); }
However, if I do this:
template <typename A> auto doit(A& a) -> decltype(takes_int_ref(convert_it(a)), void())
it does not work because invalid initialization of non-const reference of type 'int&' from an rvalue of type 'int' .
I thought of the following solution that works:
template <typename T> T& gimme_ref(T t) { throw std::runtime_error("No"); return t; } template <typename A> auto doit(A& a) -> decltype(takes_int_ref(gimme_ref(convert_it(a))), void())
However, it seems decltype , and decltype no longer reflects what the function body does. Essentially, the problem is that decltype only accepts an expression, while two statements are required in the function body.
What would be the right approach?
source share