c++ - Pattern-match/SFINAE on parameterization of container for specific classes? -
i have base
class , derived
classes. bit patterns come in external code can make these, , there generic code builds them. generic code has use explicit template "factory":
auto d = factory<d>(data); // d derived class
this factory sfinae-enabled classes derived base:
template< class t, typename = typename std::enable_if< std::is_base_of<base, t>::value >::type > t factory(externaldata &data) { t result; if (!result.initfromdata(&data)) throw std::runtime_error("data not set"); return result; }
i'd add variant works std::experimental::optional<derived>
cases when bit patterns indicate things unset. in case generic code passing in either type:
auto dod = factory<dod>(data); // dod can derived or std::optional<derived>
using explicit parameterization this, how create sfinae variant "pattern match" existence for std::experimental::optional<any class base base>
?
the desire if write:
template< std::experimental::optional<class t>, // imaginary typename = typename std::enable_if< std::is_base_of<base, t>::value >::type > std::optional<t> factory(externaldata &data) { t result; if (!result.initfromdata(&data)) return nullopt; return result; }
is there non-imaginary version of implementing desire? looked @ "using sfinae template class specialisation" (and several others) , seems maybe there ways cooperatively hack container if wrote (?), missing easy answer?
#include <type_traits> template <typename t> struct extract_optional; template <typename t> struct extract_optional<std::experimental::optional<t>> { using type = t; }; template <typename t> using extract_optional_t = typename extract_optional<t>::type; template < typename t, typename op = extract_optional_t<t>, typename = typename std::enable_if< std::is_base_of<base, op>::value >::type > std::experimental::optional<op> factory(externaldata &data) { op result; if (!result.initfromdata(&data)) return nullopt; return result; }
Comments
Post a Comment