C++ Guru Question

Wondering about this… template argument deduction succeeds for the explicitly-typed variable, fails in the auto case. (Also, it succeeds either way for an equivalently-typed unary operator template).

template <typename T>
struct Foo
{
  T m_t;
};
 
template <typename T, typename U>
Foo<U> operator/=(Foo<T> foo, function<Foo<U>(T)> fn)
{
  return fn(foo.m_t);
}
 
void mystery()
{
  auto foo = Foo<int>{1};
 
  // this works...
  function<Foo<int>(int)> f1 = [] (int i) { return Foo<int>{i}; };
  auto bar1 = foo /= f1;
 
  // this doesn't
  auto f2 = [] (int i) { return Foo<int>{i}; };
  auto bar2 = foo /= f2;
 
  // clang++ 3.3-16ubuntu1 says:
  // file:line:col: error: no viable overloaded '/='
  // auto bar2 = foo /= f2;
  //             ~~~ ^  ~~
 
  // file:line:col: note: candidate template ignored: could not match
  // 'function<Foo<type-parameter-0-1> (type-parameter-0-0)>' against
  // '<lambda at file:line:col>'
  // Foo<U> operator/=(Foo<T> foo, std::function<Foo<U>(T)> fn)
  //        ^
}

(followup to this)

Leave a Reply