Sfinae on函数具有零个或一个参数

时间:2014-04-01 06:57:36

标签: c++ c++11 metaprogramming overloading sfinae

考虑以下两个声明:

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来约束重载?

1 个答案:

答案 0 :(得分:0)

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

#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);