Boost logo

Boost :

Subject: Re: [boost] [guidelines] why template errors suck
From: Eric Niebler (eric_at_[hidden])
Date: 2010-09-27 21:06:05


On 9/27/2010 6:35 PM, David Abrahams wrote:
> At Mon, 27 Sep 2010 18:09:16 -0400, Eric Niebler wrote:
>> And yet nobody can tell me how to actually use concepts to implement
>> my libraries and improve error messages.
>
> I know you know the generic programming process, since we taught a
> course on it together. You have to start at the beginning and
> discover the concepts by looking at concrete algorithms, lifting out
> common requirements, and clustering those into concepts. If that
> doesn't work in your problem domain, concepts might not be an
> appropriate mechanism for what you want to. But I wouldn't draw any
> conclusions about what's possible without first trying it.

I think so far I have failed to make my use case sufficiently clear, so
I'll simplify and try to follow the Process. Take the following simple
algorithm sum_ints:

  template<class First, class Second>
  int sum_ints_impl( std::pair<First, Second> const & p )
  {
      return sum_ints_impl(p.first) + sum_ints_impl(p.second);
  }

  int sum_ints_impl( int i )
  {
      return i;
  }

  template<class T>
  int sum_ints( T const & t )
  {
      return sum_ints_impl( t );
  }

Should be self explanatory. sum_ints accepts ints or std::pairs of ints,
or std::pairs of std::pairs of ints, etc. Now, I'd like to concept-check
the argument to sum_ints. What can I say about it? It must be something
I can pass to sum_ints_impl. That means it must be an int or a
std::pair. How shall I define this int-or-std::pair concept?

So I look for requirements. Let's say there is a concept Integer that is
satisfied for type int. Let's also say we define a concept Pair that
checks for the presence of members "first" and "second". Finally, let's
define a concept "SumIntsAble"---that is the concept that must be
satisfied by the argument to the sum_ints algorithm. To me, it seems
like SumIntsAble<T> is "Integer<T> || Pair<T>". (Actually, it's more
complicated than that because we must also check that Pair's first and
second members are also SumIntsAble, but let's skip that.)

There is no such thing as OR constraints, but as you say we can fake it
with concept maps. As a result, the concept SumIntsAble takes the
intersection of the two concepts Integer and Pair. Which is nothing
interesting. We wouldn't be able to call the first sum_ints_impl because
that function requires "first" and "second" data members (which aren't
present in the Integer concept). And we can't call the second because
that requires that the parameter is convertible to int (which Pair does
not enforce).

I'm stuck.

Can you show me how you would approach this problem?

-- 
Eric Niebler
BoostPro Computing
http://www.boostpro.com

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