Boost logo

Boost :

From: Noah Roberts (roberts.noah_at_[hidden])
Date: 2007-03-12 13:06:59


Douglas Gregor wrote:

> concept IsFloating<typename T> { }
>
> You could then use IsFloating like a type trait (a yes or no answer),
> but it wouldn't get you very far. For instance, you can't write any
> interesting algorithms with it:
>
> template<typename T>
> requires IsFloating<T>
> T negate(T x) { return -x; }
>
> The compiler would reject this, because there is no negation operator.
> Why? Well, we interpret the name IsFloating to mean that the type has
> certain properties, including a negation operator. Traits work this way,
> with the implication that the programmer knows what all of the
> properties are for a given trait. Since templates aren't really
> type-checked, it works (until it doesn't work; then you get the long
> error messages).
>
> The compiler can't interpret the name IsFloating, so it looks in the
> concept bodies to see what properties the type should have. We don't
> list any properties in the IsFloating concept, so we can do nothing with
> our template type parameter T.
>
> This is why you don't see "Is" or "Has" in a concept name... concepts
> specify exactly what properties we expect a type to have. So, we might
> write a Floating concept like this:
>
> concept Floating<typename T> {
> T operator-(T);
> T operator+(T, T);
> T operator-(T, T);
> T operator*(T, T);
> T operator/(T, T);
> // ...
> }
>
> Every floating-point type has those properties, so they meet the
> requirements of the Floating concept, and we can write our negate
> algorithm:
>
> template<typename T>
> requires Floating<T>
> T negate(T x) { return -x; }

I'm still trying to get the video to load...damn google videos can never
seem to complete... so if this is answered in the video forgive me for
asking again.

Will this allow me to instantiate based on what concept is followed?
For instance, with traits I might do something like the following:

template <typename T>
struct is_floating { static bool const value = true; };

template <typename T>
typename enable_if<is_floating<T>, bool>::type f(T value) {...}

template <typename T>
typename enable_if<is_somethingelse<T>, bool>::type f(T value) {...}

I rather started to disregard boost::concepts because I couldn't find a
way to do this with them and type traits could be equally expressive so
that they completely describe the concepts you are trying to get.


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk