具有零或一个参数的函数上的 Sfinae

Sfinae on function with either zero or one parameter

本文关键字:参数 一个 函数 Sfinae      更新时间:2023-10-16

请考虑以下两个声明:

template <class Function, 
          class = typename std::enable_if</*Function has zero argument*/>::type>
void apply(Function&& function);
template <class Function, 
          class... Dummy,
          class = typename std::enable_if</*Function has one argument*/>::type,
          class = typename std::enable_if<sizeof...(Dummy) == 0>::type>
void apply(Function&& function, Dummy...);

在第一种和第二种情况下,当函数有零个或一个参数(无论参数的类型如何)时,我应该在std::enable_if中放入什么来约束重载?

以下特征可能会对您有所帮助:

#include <type_traits>
#include <functional>
template <typename T>
struct arity : public arity<decltype(&T::operator())> {};
template <typename C, typename Ret, typename... Args>
struct arity<Ret(C::*)(Args...) const> :
    std::integral_constant<std::size_t, sizeof...(Args)>
{
};
// Do the same for other (11) combination of volatile, const, reference method.
// function pointer
template<class R, class... Args>
struct arity<R(*)(Args...)> : public arity<R(Args...)>
{};
template<class R, class... Args>
struct arity<R(Args...)> : std::integral_constant<std::size_t, sizeof...(Args)>
{
};

然后

template <class Function,
          class = typename std::enable_if<arity<typename std::remove_reference<Function>::type>::value == 0>::type>
void apply(Function&& function);
相关文章: