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

Why Reading Books Matters to a Programmer

29 April, 200829 April, 2008

The programming book market these days is small. Nothing like what it was eight years ago or so. And apparently, programmers don’t read books (any more). It’s mostly true. But of course, there are still books worth reading. I’m going to take as read the easy arguments: let’s assume that…

Read More

How to print anything in C++ (part 5)

2 February, 201530 June, 2015

Part 1 Part 2 Part 3 Part 4 Part 5 Postscript So far, we can print containers, but what about arrays? And what about “pretty-printing” strings – perhaps we need to wrap them with quotes. Well, we know that with the existing code, both arrays and strings count as outputtable….

Read More

A Crossword for CppCon 2025 – Solutions

22 September, 202522 September, 2025

See https://www.elbeno.com/blog/?p=1795 (or https://crosshare.org/crosswords/aZ0lpCTDSztWEsvvuboa/cppcon-2025) if you want to try it. If you’re here for solutions, read on. Definitions are given in italics. My personal likes are 4D and 13D. 1A BABBAGE Supergroup among leaders to back grant endowment for computing pioneer (7) ABBA (“supergroup”) inserted into (“among”) BGE (“leaders to…

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