10

我想编写一个is_callable<F, Arg>定义value为的 C++ 元函数true,当且仅当类型 F 具有形式的函数调用运算符时SomeReturnType operator()(const Arg &)。例如,在以下情况下

struct foo {
  void operator(const int &) {}
};

我想is_callable<foo, int &>成为falseis_callable<foo, const int &>成为true。这是我到目前为止所拥有的:

#include <memory>
#include <iostream>

template<typename F, typename Arg>
struct is_callable {
private:

  template<typename>
  static char (&test(...))[2];

  template<unsigned>
  struct helper {
    typedef void *type;
  };

  template<typename UVisitor>
  static char test(
               typename helper<
                 sizeof(std::declval<UVisitor>()(std::declval<Arg>()), 0)
                 >::type
               );
public:
  static const bool value = (sizeof(test<F>(0)) == sizeof(char));
};

struct foo {
  void operator()(const int &) {}
};

using namespace std;

int main(void)
{
  cout << is_callable<foo, int &>::value << "\n";
  cout << is_callable<foo, const int &>::value << "\n";

  return 0;
}

这打印1and 1,但我想要0and1因为foo只定义void operator()(const int &).

4

6 回答 6

9

经过几个小时的玩耍和C++ 聊天室中的一些认真讨论,我们终于得到了一个版本,该版本适用于可能重载或继承的函子operator()以及函数指针,基于 @KerrekSB 和 @BenVoigt 的版本。

#include <utility>
#include <type_traits>

template <typename F, typename... Args>
class Callable{
  static int tester[1];
  typedef char yes;
  typedef yes (&no)[2];

  template <typename G, typename... Brgs, typename C>
  static typename std::enable_if<!std::is_same<G,C>::value, char>::type
      sfinae(decltype(std::declval<G>()(std::declval<Brgs>()...)) (C::*pfn)(Brgs...));

  template <typename G, typename... Brgs, typename C>
  static typename std::enable_if<!std::is_same<G,C>::value, char>::type
      sfinae(decltype(std::declval<G>()(std::declval<Brgs>()...)) (C::*pfn)(Brgs...) const);

  template <typename G, typename... Brgs>
  static char sfinae(decltype(std::declval<G>()(std::declval<Brgs>()...)) (G::*pfn)(Brgs...));

  template <typename G, typename... Brgs>
  static char sfinae(decltype(std::declval<G>()(std::declval<Brgs>()...)) (G::*pfn)(Brgs...) const);

  template <typename G, typename... Brgs>
  static yes test(int (&a)[sizeof(sfinae<G,Brgs...>(&G::operator()))]);

  template <typename G, typename... Brgs>
  static no test(...);

public:
  static bool const value = sizeof(test<F, Args...>(tester)) == sizeof(yes);
};

template<class R, class... Args>
struct Helper{ R operator()(Args...); };
 
template<typename R, typename... FArgs, typename... Args>
class Callable<R(*)(FArgs...), Args...>
  : public Callable<Helper<R, FArgs...>, Args...>{};

Ideone 上的实时示例。请注意,两个失败的测试是重载operator()测试。这是一个带有可变参数模板的 GCC 错误,已在 GCC 4.7 中修复。Clang 3.1 还将所有测试报告为passed.

如果您希望operator()默认参数失败,有一种可能的方法可以做到这一点,但是其他一些测试将在那时开始失败,我发现尝试纠正它太麻烦了。

编辑:正如@Johannes 在评论中正确指出的那样,我们在这里有点不一致,即定义转换为函数指针的函子不会被检测为“可调用”。这是,恕我直言,修复起来非常重要,因此我不会打扰它(现在)。如果你绝对需要这个特性,那么,留下评论,我会看看我能做什么。


既然这一切都已经说了,恕我直言,这个特征的想法是愚蠢的。为什么你有这么确切的要求?为什么标准is_callable不够?

(是的,我认为这个想法很愚蠢。是的,我仍然去建造了这个。是的,这很有趣,非常有趣。不,我没有疯。至少这是我所相信的......)

于 2012-01-18T08:57:26.907 回答
7

(对 Kerrek 以他的回答为出发点表示歉意)

编辑:更新以处理没有任何类型operator()的类型。

#include <utility>

template <typename F, typename Arg>
struct Callable
{
private:
  static int tester[1];
  typedef char                      yes;
  typedef struct { char array[2]; } no;

  template <typename G, typename Brg>
  static char sfinae(decltype(std::declval<G>()(std::declval<Brg>())) (G::*pfn)(Brg)) { return 0; }

  template <typename G, typename Brg>
  static char sfinae(decltype(std::declval<G>()(std::declval<Brg>())) (G::*pfn)(Brg) const) { return 0; }

  template <typename G, typename Brg>
  static yes test(int (&a)[sizeof(sfinae<G,Brg>(&G::operator()))]);

  template <typename G, typename Brg>
  static no test(...);

public:
  static bool const value = sizeof(test<F, Arg>(tester)) == sizeof(yes);
};

struct Foo
{
  int operator()(int &) { return 1; }

};

struct Bar
{
  int operator()(int const &) { return 2; }
};

struct Wazz
{
  int operator()(int const &) const { return 3; }
};

struct Frob
{
  int operator()(int &) { return 4; }
  int operator()(int const &) const { return 5; }
};

struct Blip
{
  template<typename T>
  int operator()(T) { return 6; }
};

struct Boom
{

};

struct Zap
{
  int operator()(int) { return 42; }
};

#include <iostream>
int main()
{
  std::cout << "Foo(const int &):  " << Callable<Foo,  int const &>::value << std::endl
            << "Foo(int &):        " << Callable<Foo,  int &>::value << std::endl
            << "Bar(const int &):  " << Callable<Bar,  const int &>::value << std::endl
            << "Bar(int &):        " << Callable<Bar,  int &>::value << std::endl
            << "Zap(const int &):  " << Callable<Zap , const int &>::value << std::endl
            << "Zap(int&):         " << Callable<Zap , int &>::value << std::endl
            << "Wazz(const int &): " << Callable<Wazz, const int &>::value << std::endl
            << "Wazz(int &):       " << Callable<Wazz, int &>::value << std::endl
            << "Frob(const int &): " << Callable<Frob, const int &>::value << std::endl
            << "Frob(int &):       " << Callable<Frob, int &>::value << std::endl
            << "Blip(const int &): " << Callable<Blip, const int &>::value << std::endl
            << "Blip(int &):       " << Callable<Blip, int &>::value << std::endl
            << "Boom(const int &): " << Callable<Boom, const int &>::value << std::endl
            << "Boom(int&):        " << Callable<Boom, int &>::value << std::endl;
}

演示:http: //ideone.com/T3Iry

于 2012-01-18T04:04:17.027 回答
2

可能是这样的?让它在 VS2010 上工作有点绕。

template<typename FPtr>
struct function_traits_impl;

template<typename R, typename A1>
struct function_traits_impl<R (*)(A1)>
{
    typedef A1 arg1_type;
};

template<typename R, typename C, typename A1>
struct function_traits_impl<R (C::*)(A1)>
{
    typedef A1 arg1_type;
};

template<typename R, typename C, typename A1>
struct function_traits_impl<R (C::*)(A1) const>
{
    typedef A1 arg1_type;
};

template<typename T>
typename function_traits_impl<T>::arg1_type arg1_type_helper(T);

template<typename F>
struct function_traits
{
    typedef decltype(arg1_type_helper(&F::operator())) arg1_type;
};

template<typename F, typename Arg>
struct is_callable : public std::is_same<typename function_traits<F>::arg1_type, const Arg&>
{
}
于 2012-01-18T01:54:02.963 回答
2

这是我破解的东西,可能是你需要的,也可能不是你需要的;它似乎确实为(const) int &...提供了真(假)

#include <utility>

template <typename F, typename Arg>
struct Callable
{
private:
  typedef char                      yes;
  typedef struct { char array[2]; } no;

  template <typename G, typename Brg>
  static yes test(decltype(std::declval<G>()(std::declval<Brg>())) *);

  template <typename G, typename Brg>
  static no test(...);

public:
  static bool const value = sizeof(test<F, Arg>(nullptr)) == sizeof(yes);
};

struct Foo
{
  int operator()(int &) { return 1; }
  // int operator()(int const &) const { return 2; } // enable and compare
};

#include <iostream>
int main()
{
  std::cout << "Foo(const int &): " << Callable<Foo, int const &>::value << std::endl
            << "Foo(int &):       " << Callable<Foo, int &>::value << std::endl
    ;
}
于 2012-01-18T03:14:24.390 回答
2

这是一个可能的解决方案,它利用额外的测试来查看您的模板是否被实例化const T&

#include <memory>
#include <iostream>

using namespace std;

template<typename F, typename Arg>
struct is_callable {
private:

  template<typename>
  static char (&test(...))[2];

  template<bool, unsigned value>
  struct helper {};

  template<unsigned value>
  struct helper<true, value> {
    typedef void *type;
  };

  template<typename T>
  struct is_const_ref {};

  template<typename T>
  struct is_const_ref<T&> {
    static const bool value = false;
  };

  template<typename T>
  struct is_const_ref<const T&> {
    static const bool value = true;
  };

  template<typename UVisitor>
  static char test(typename helper<is_const_ref<Arg>::value, 
                                   sizeof(std::declval<UVisitor>()(std::declval<Arg>()), 0)>::type);
public:
  static const bool value = (sizeof(test<F>(0)) == sizeof(char));
};

struct foo {
  void operator()(const int &) {}
};

int main(void)
{
  cout << is_callable<foo, int &>::value << "\n";
  cout << is_callable<foo, const int &>::value << "\n";

  return 0;
}
于 2012-01-18T04:10:08.667 回答
0

在做其他事情时遇到了这个问题,能够调整我的代码以适应。它具有与@Xeo 相同的功能(和限制),但不需要 sizeof 技巧/enable_if。默认参数代替了需要执行 enable_if 来处理模板函数。我使用 Xeo 编写的相同测试代码在 g++ 4.7 和 clang 3.2 下对其进行了测试

#include <type_traits>
#include <functional>

namespace detail {
  template<typename T, class Args, class Enable=void>
  struct call_exact : std::false_type {};

  template<class...Args> struct ARGS { typedef void type; };

  template<class T, class ... Args, class C=T>
  C * opclass(decltype(std::declval<T>()(std::declval<Args>()...)) (C::*)(Args...)) { }
  template<class T, class ... Args, class C=T>
  C * opclass(decltype(std::declval<T>()(std::declval<Args>()...)) (C::*)(Args...) const) { }

  template<typename T, class ... Args>
  struct call_exact<T, ARGS<Args...>,
    typename ARGS<
       decltype(std::declval<T&>()(std::declval<Args>()...)),
       decltype(opclass<T, Args...>(&T::operator()))
     >::type
   > : std::true_type {};
}

template<class T, class ... Args>
struct Callable : detail::call_exact<T, detail::ARGS<Args...>> { };

template<typename R, typename... FArgs, typename... Args>
struct Callable<R(*)(FArgs...), Args...>
 : Callable<std::function<R(FArgs...)>, Args...>{};
于 2013-03-28T23:52:36.853 回答