|
Boost Users : |
Subject: Re: [Boost-users] [MPL] implementing a "trait"?
From: Alex (alexhighviz_at_[hidden])
Date: 2014-02-08 12:44:50
-----Original Message-----
From: Boost-users [mailto:boost-users-bounces_at_[hidden]] On Behalf Of
Alex
Sent: 07 February 2014 18:48
To: boost-users_at_[hidden]
Subject: Re: [Boost-users] [MPL] implementing a "trait"?
-----Original Message-----
From: Boost-users [mailto:boost-users-bounces_at_[hidden]] On Behalf Of
John M. Dlugosz
I want to mark certain types as being of a category of my invention (e.g.
is_pretty), for purposes of using enable_if in the same manner is standard
type traits such as is_arithmetic etc.
The trait will be false by default, and I'd declare something to nominate
types that should be seen to have that trait. I want it to follow
inheritance; if B has been declared to be in my category, and C is derived
from B, then C will also be in that category without needing to do anything
more (though some way to turn it _off_ would be available).
-----End Original Message-----
Now have a simpler solution:
#include <iostream>
#include <type_traits>
#include <utility>
class A{}; //pretty;
class B{}; // not pretty
class C : public A{}; // pretty because it derives from A
class D : public A{}; // not pretty even though it derives from A
// default because conversion pointer-to-bool has lowest overload precedence
std::false_type is_pretty_function(bool);
// set the traits for A and D
std::true_type is_pretty_function(A*);
std::false_type is_pretty_function(D*);
// use this struct to "read" the traits from the functions
template<class T> struct trait
{
typedef decltype(is_pretty_function(std::declval<T*>())) is_pretty;
};
int main()
{
std::cout << "A looks " << (trait<A>::is_pretty::value ? "pretty": "nice"
)<<std::endl;
std::cout << "B looks " << (trait<B>::is_pretty::value ? "pretty": "nice"
)<<std::endl;
std::cout << "C looks " << (trait<C>::is_pretty::value ? "pretty": "nice"
)<<std::endl;
std::cout << "D looks " << (trait<D>::is_pretty::value ? "pretty": "nice"
)<<std::endl;
return 0;
}
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net