|
Boost : |
Subject: Re: [boost] IS THERE A WAY TO FIND IF A CERTAIN TYPE HAS A CERTAIN MEMBER?
From: Paul Fultz II (pfultz2_at_[hidden])
Date: 2016-01-14 20:28:01
With clang in Boost.Hana you can use `hana:overload_linearly`:
template<class T>
void optional_foo(T&& x)
{
boost::hana::overload_linearly(
// Call foo if it exists
[](auto&& x) -> decltype(x.foo(), void()) { x.foo(); },
[](auto) { std::cout << "No foo" << std::endl; }
)(x);
}
However, if you need more portability(such as running on MSVC), you can use
`fit::conditional` as well:
http://fit.readthedocs.org/en/latest/conditional/index.html
Although its not yet a boost library, it is in the review queue and can work
for MSVC and C++11 compilers. With the Fit library you can also define the
function directly from the lambdas as well:
FIT_STATIC_LAMBDA_FUNCTION(optional_foo) = fit::conditional(
// Call foo if it exists
[](auto&& x) -> decltype(x.foo(), void()) { x.foo(); },
[](auto) { std::cout << "No foo" << std::endl; }
);
This still requires generic lambdas. If you are stuck in a C++11 compiler,
you
can write it using function objects as well:
struct with_foo
{
template<class T>
auto operator()(T&& obj) const -> decltype(x.foo(), void())
{
x.foo();
}
};
struct without_foo
{
template<class T>
void operator()(T&&) const
{
std::cout << "No foo" << std::endl;
}
};
FIT_STATIC_FUNCTION(optional_foo) = fit::conditional(
with_foo(),
without_foo()
);
If you are stuck in C++03 land, though, you will need to use Boost.TTI
Thanks,
Paul
On Thursday, January 14, 2016 at 1:43:09 PM UTC-6, Juan Dent wrote:
>
> > HI,
> >
> >
> > I have read that via enable_if and other constructs, one can declare a
> member of a type conditionally.
> >
> > What I need is a way to be able to test whether a certain type has a
> certain method or member data, so that I can call it or use it accordingly.
> >
> > Does boost have something like this??
> >
> >
> > Regards,
> > Juan
>
>
> _______________________________________________
> Unsubscribe & other changes:
> http://lists.boost.org/mailman/listinfo.cgi/boost
>
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk