Friday, October 16, 2020

Validating lambda signatures in C++17

WinLamb, as the name itself implies, is heavily based on lambda functions. While searching a way to enforce the lambda signatures in the upcoming C++17 release, I received an incredible answer on StackOverflow:

#include <functional>
#include <type_traits>
	
template<typename F>
auto foo(F&& func) noexcept ->
	std::enable_if_t<
		std::is_same_v<
			decltype(std::function{std::forward<F>(func)}),
			std::function<void(int)>
		>, void
	>
{
	func(33);
}

Up to this point, I was completely unaware of the existence of trailing return types in function declarations.

The validation is extremely restrict, serving my purposes perfectly. And it seems that the upcoming C++20 concepts feature can simplify it quite a lot.