Skip to content
Why is a raven like a writing desk?

Thoughts both confusing and enlightening.

Why is a raven like a writing desk?

Thoughts both confusing and enlightening.

C++ Guru Question – followup

elbeno, 12 August, 201430 June, 2015

(following on from C++ Guru Question)

There are a few reasons why the code before didn’t work: mainly

a) C++ template argument deduction works one-way with a list of candidates, it’s not H-M type inference.
b) A C++ lambda is a thing with some internal type, not a std::function (although it can be assigned to one, that doesn’t matter for template type deduction).

Anyway, a reasonable solution to this problem is to simplify the template argument matching to the function type, and use a simple function_traits template to take apart the function argument and return types.

template 
struct function_traits
  : public function_traits
{};

template 
struct function_traits
{
  typedef R returnType;
  typedef A argType;
};

template 
struct function_traits
  : public function_traits
{};

template 
struct Foo
{
  T m_t;
};

template 
typename function_traits::returnType operator/=(
    Foo::argType> foo, const F& fn)
{
  return fn(foo.m_t);
}

void mystery()
{
  auto foo = Foo{1};

  // this works...
  function(int)> f1 = [] (int i) { return Foo{i}; };
  auto bar1 = foo /= f1;

  // this does too!
  auto f2 = [] (int i) { return Foo{i}; };
  auto bar2 = foo /= f2;
}
C++ Programming

Post navigation

Previous post
Next post

Related Posts

An Interesting C++ Technique

26 August, 201330 June, 2015

I recently discovered a C++ technique I haven’t seen recognized before in any books, articles, or mentioned online anywhere (search terms are difficult perhaps). For want of a better name I call it Structural Capture. Consider the following code: #include #include using namespace std; //————————————————————— struct Foo { template Foo(const…

Read More

Experimenting with constexpr

13 October, 201515 October, 2015

Since seeing Scott Schurr at C++Now in Aspen and hearing his talks about constexpr, it’s been on my list of things to try out, and recently I got around to it. With the release of Visual Studio 2015, Microsoft’s compiler now finally supports C++11 style constexpr (modulo some minor issues),…

Read More

More string hashing with C++11 constexpr

14 October, 201515 October, 2015

(Start at the beginning of the series – and all the source can be found in my github repo) So FNV1 was easy, and Murmur3 wasn’t too much harder; for a challenge and to see how far I could go, I decided to try to compute an MD5 string hash…

Read More

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

©2026 Why is a raven like a writing desk? | WordPress Theme by SuperbThemes