Skip to main content

Convenient deduction guides for std::function

The objective is to allow the following to be valid C++.
#include <functional>
struct Test {
  void func(int) {}
};
void test() {
  std::function deduced = &Test::func; // compiler error
  std::function<void (Test *, int)> ex = &Test::func; // OK
}
With class template argument deduction in C++17, type arguments for std::function above should have been deduced. The first line in function test fails to compile as of this writing because std::function does not appear to have deduction guides for conversion from pointer to member functions. On the other hand, explicitly specifying the template arguments makes the compiler happy.

The following deduction guide seems to fix the issue.
namespace std { // warning: undefined behavior
  template<class R, class C, class... ArgTypes> 
  function(R(C::*)(ArgTypes...)) -> function<R(C*, ArgTypes...)>;
}
void test() {
  std::function deduced = &Test::func; // Now, OK
  std::function<void (Test *, int)> ex = &Test::func;
  Test test;
  deduced(&test, 10); // Calls test.func(10)
  ex(&test, 10); // Calls test.func(10)
}
However, the above code is technically undefined behavior because a user-defined deduction guide for a standard library type is added in std namespace. Clang does not like it either. Gcc may start rejecting this code in (near) future.

Weirdly, deduction guides must be defined in the same scope where the primary template is defined. That means, writing custom deduction guides for standard library types is out of question. Not sure how I feel about that.

Arbitrary Choice

There's another problem. In the deduction guide above, I made an arbitrary choice that the deduced std::function is callable with a pointer to Test. That's arbitrary. What about Test&?

PtrCallable and RefCallable

I added two types that specify how the function will be called. This time in my own namespace.
namespace callable {
template <class... Args>
struct PtrCallable : std::function<Args...> {
  using std::function<Args...>::function; // inherited constructors
};

template <class... Args>
struct RefCallable : std::function<Args...> {
  using std::function<Args...>::function; // inherited constructors
};

// Deduction guides for the newly introduced types
template<class R, class C, class... ArgTypes> 
PtrCallable(R(C::*)(ArgTypes...)) -> PtrCallable<R(C*, ArgTypes...)>;

template<class R, class C, class... ArgTypes> 
RefCallable(R(C::*)(ArgTypes...)) -> RefCallable<R(C&, ArgTypes...)>;
} // namespace callable
Now the choice is not arbitrary. User can pick one.
using namespace callable;
void test() {
  RefCallable deduced1 = &Test::func;
  PtrCallable deduced2 = &Test::func;
  Test test;
  deduced1(test, 10); // Calls test.func(10)
  deduced2(&test, 10); // Calls (&test)->func(10)
}

More deduction guides for const and volatile

More deduction guides are needed to support other varieties of member functions. Let's add them.
namespace callable {
template<class R, class C, class... ArgTypes> 
PtrCallable(R(C::*)(ArgTypes...) const) -> PtrCallable<R(const C*, ArgTypes...)>;

template<class R, class C, class... ArgTypes> 
RefCallable(R(C::*)(ArgTypes...) const) -> RefCallable<R(const C&, ArgTypes...)>;

// ditto for volatile and const volatile 

} // namespace callable

Deduction guides for rvalue-ref qualified member functions

Even more deduction guides are needed for rvalue-ref qualified member functions
namespace callable {
template<class R, class C, class... ArgTypes> 
RefCallable(R(C::*)(ArgTypes...) &&) -> RefCallable<R(C&&, ArgTypes...)>;

template<class R, class C, class... ArgTypes> 
RefCallable(R(C::*)(ArgTypes...) const &&) -> RefCallable<R(const C&&, ArgTypes...)>;

// ditto for volatile and const volatile
} // namespace callable

Conclusion

With a dozen or so new deduction guides all the following cases work. Runnable code is shared on Wandbox.
const Test getConstTest() {
  return {};   
}
void test_function() {
   std::function<void(Test*, int)> f1 = &Test::Nonconst;
   std::function<void(const Test*, int)> f2 = &Test::Const;
   Test a;
   const Test c;
   f1(&a, 1);
   f2(&c, 1.0);
}

void test_refcallable() {
   using namespace callable;
   Test a;
   const Test c;
   RefCallable f1 = &Test::Nonconst;
   f1(a, 1);
   RefCallable f2 = &Test::Const;
   f2(a, 1);
   f2(c, 1);
   RefCallable f3 = &Test::rvalue;
   f3(Test{}, 10); 
   RefCallable f4 = &Test::rvalue_const;
   f4(getConstTest(), 10); 
}

void test_ptrcallable() {
   using namespace callable;
   Test a;
   const Test c;
   PtrCallable f1 = &Test::Nonconst;
   f1(&a, 1);
   PtrCallable f2 = &Test::Const;
   f2(&a, 1);
   f2(&c, 1);
}

Comments

Popular Content

Unit Testing C++ Templates and Mock Injection Using Traits

Unit testing your template code comes up from time to time. (You test your templates, right?) Some templates are easy to test. No others. Sometimes it's not clear how to about injecting mock code into the template code that's under test. I've seen several reasons why code injection becomes challenging. Here I've outlined some examples below with roughly increasing code injection difficulty. Template accepts a type argument and an object of the same type by reference in constructor Template accepts a type argument. Makes a copy of the constructor argument or simply does not take one Template accepts a type argument and instantiates multiple interrelated templates without virtual functions Lets start with the easy ones. Template accepts a type argument and an object of the same type by reference in constructor This one appears straight-forward because the unit test simply instantiates the template under test with a mock type. Some assertion might be tested in...

Covariance and Contravariance in C++ Standard Library

Covariance and Contravariance are concepts that come up often as you go deeper into generic programming. While designing a language that supports parametric polymorphism (e.g., templates in C++, generics in Java, C#), the language designer has a choice between Invariance, Covariance, and Contravariance when dealing with generic types. C++'s choice is "invariance". Let's look at an example. struct Vehicle {}; struct Car : Vehicle {}; std::vector<Vehicle *> vehicles; std::vector<Car *> cars; vehicles = cars; // Does not compile The above program does not compile because C++ templates are invariant. Of course, each time a C++ template is instantiated, the compiler creates a brand new type that uniquely represents that instantiation. Any other type to the same template creates another unique type that has nothing to do with the earlier one. Any two unrelated user-defined types in C++ can't be assigned to each-other by default. You have to provide a...

Multi-dimensional arrays in C++11

What new can be said about multi-dimensional arrays in C++? As it turns out, quite a bit! With the advent of C++11, we get new standard library class std::array. We also get new language features, such as template aliases and variadic templates. So I'll talk about interesting ways in which they come together. It all started with a simple question of how to define a multi-dimensional std::array. It is a great example of deceptively simple things. Are the following the two arrays identical except that one is native and the other one is std::array? int native[3][4]; std::array<std::array<int, 3>, 4> arr; No! They are not. In fact, arr is more like an int[4][3]. Note the difference in the array subscripts. The native array is an array of 3 elements where every element is itself an array of 4 integers. 3 rows and 4 columns. If you want a std::array with the same layout, what you really need is: std::array<std::array<int, 4>, 3> arr; That's quite annoying for...