|
Boost Users : |
Subject: Re: [Boost-users] [MPL] implementing a "trait"?
From: Alex (alexhighviz_at_[hidden])
Date: 2014-02-07 13:47:33
-----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-----
The following works for me, but I am not sure if it is because of a working or a failing compiler:
Best wishes, Alex
#include <iostream>
#include <string>
#include <type_traits>
#include <utility>
class A{}; //is_pretty;
class B{}; // don't know
class C : public A{}; // is_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);
std::true_type is_pretty_function(A*);
std::false_type is_pretty_function(D*);
struct is_pretty_object
{
template <typename T>
auto operator()(T&& t) -> decltype(is_pretty_function(std::forward<T>(t))) {
return is_pretty_function(std::forward<T>(t));
}
};
template<class T>
struct trait
{
typedef typename std::result_of<is_pretty_object(T*)>::type 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;
}
http://www.compileonline.com/compile_cpp11_online.php
A looks pretty
B looks nice
C looks pretty
D looks nice
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