c++ - Turn casting / construction into a perfect forwardable function -



c++ - Turn casting / construction into a perfect forwardable function -

sscce:

#include <functional> using std::function; using std::forward; template<typename totype, typename... fromtypes> totype construct(fromtypes&&... fromtypes) { homecoming totype(forward<fromtypes>(fromtypes)...); } class maybe { public: maybe() : m_value(42.0f) {} template<typename function> auto apply(function function) const -> decltype(function(std::declval<float>())) { homecoming function(value()); } private: float const& value() const { homecoming m_value; } float m_value; }; int main() { maybe a; a.apply(construct<int, float>); homecoming 0; }

gives error:

test.cpp: in instantiation of ‘decltype (function(declval<float>())) maybe::apply(function) const [with function = int (*)(float&&); decltype (function(declval<float>())) = int]’: test.cpp:31:32: required here test.cpp:17:28: error: invalid initialization of reference of type ‘float&&’ look of type ‘const float’ homecoming function(value()); ^

from error message, it's problem fact value() returns const&.

the key point here, type isn't beingness deduced on line 17, value beingness passed it. type beingness assigned when construct function passed apply on line 31.

i specified wrong type template of construct. construct<int, float>. if utilize construct<int, float const&> functions fine.

however, cumbersome , requires knowledge of implementation of apply. , never ever bind lvalue, because t , t&& different types. (because of lack of type deduction.)

is there way have function can pass function , have type deduction occur @ site called, can have perfect forwarding happen more or less transparently callers? or there way accomplish end doesn't leak complexity caller?

how this?

#include <functional> using std::function; using std::forward; template<typename totype> class build { public: template<typename... fromtypes> totype operator()(fromtypes&&... fromtypes) { homecoming totype(forward<fromtypes>(fromtypes)...); } }; class maybe { public: maybe() : m_value(42.0f) {} template<typename function> auto apply(function function) const -> decltype(function(std::declval<float>())) { homecoming function(value()); } private: float const& value() const { homecoming m_value; } float m_value; }; int main() { maybe a; a.apply(construct<int>()); homecoming 0; }

you have specify type want convert cannot deduced in context have given.

c++ rvalue-reference perfect-forwarding universal-reference

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

django - Access session in user model .save() -

php - .htaccess Multiple Rewrite Rules / Prioritizing -