使用C ++检测习惯用

时间:2016-04-12 18:30:46

标签: c++ templates c++11 sfinae detection-idiom

我一直在使用C ++ detection idiom创建一个元函数来确定任意可调用的参数个数。到目前为止,我有这个(完整,可编译的代码http://ideone.com/BcgDhv):

static constexpr auto max_num_args = 127;

struct any { template <typename T> operator T() { } };

template <typename F, typename... Args>
using callable_archetype = decltype( declval<F>()(declval<Args>()...) );
template <typename F, typename... Args>
using is_callable_with_args = is_detected<callable_archetype, F, Args...>;

template <typename F, size_t I = 0,  typename... Args>
struct count_args
  : conditional<is_callable_with_args<F, Args...>::value,
      integral_constant<size_t, I>,
      count_args<F, I+1, Args..., any>
    >::type::type
{ };

template <typename F, typename... Args>
struct count_args<F, max_num_args, Args...> : integral_constant<size_t, max_num_args> { };

当没有可调用的参数是左值引用时,这很有效:

void foo(int i, int j) { }
static_assert(count_args<decltype(foo)>::value == 2, "");

但是当任何参数都是左值引用时,这会失败(原因很明显,因为可调用的原型具有替换失败):

void bar(char i, bool j, double& k);
static_assert(count_args<decltype(bar)>::value == 3, "doesn't work");

有没有人知道如何概括这个想法,以使它也适用于左值引用?

3 个答案:

答案 0 :(得分:3)

以下作品(适用于小型max_num_args):

struct any    { template <typename T> operator T(); };
struct anyref { template <typename T> operator T&(); };

template <typename F, typename... Args>
using callable_archetype = decltype(std::declval<F>()(std::declval<Args>()...) );
template <typename F, typename... Args>
using is_callable_with_args = std::is_detected<callable_archetype, F, Args...>;

template <typename F, size_t I = 0,  typename... Args>
struct count_args
  : std::conditional<is_callable_with_args<F, Args...>::value,
      std::integral_constant<std::size_t, I>,
      std::integral_constant<std::size_t,
                             std::min(count_args<F, I+1, Args..., any>::value,
                                      count_args<F, I+1, Args..., anyref>::value)>
    >::type::type
{};

template <typename F, typename... Args>
struct count_args<F, max_num_args, Args...> :
    std::integral_constant<std::size_t, max_num_args> {};

Demo

但代码必须进行优化,因为复杂性为2**max_num_args:/

答案 1 :(得分:1)

更改此行:

struct any { template <typename T> operator T() { } };

为:

struct any {
  template <typename T> operator T&&() { }
  template <typename T> operator T&() { }
};

live example

我们有一个左值和右值隐式转换运算符。那么,我们......好吗?

答案 2 :(得分:0)

基于@ Jarod42的答案,在绝大多数情况下,any的稍微更好的定义似乎可以解决问题(不包括导致callable_archetype成为其他替换错误的情况原因;例如,具有已删除的复制构造函数的类,其调用无论如何都无效):

struct any {
  template <typename T,
    typename = enable_if_t<
      not is_same<T, remove_reference_t<T>>::value
    >
  >
  operator T();

  template <typename T,
    typename = enable_if_t<
      is_same<T, remove_reference_t<T>>::value
    >
  >
  operator T&();

  template <typename T,
    typename = enable_if_t<
      is_same<T, remove_reference_t<T>>::value
    >
  >
  operator T&&();
};

这似乎适用于所有与前一个答案相同的情况,没有指数缩放。

Demo