c++ - 如何检查成员运算符(类型)?

标签 c++ templates c++11 sfinae

<分区>

假设我有类型 barfoo .如何构建模板类 has_call_with_arg<>这样 has_call_with_arg<bar,foo>::value为真当且仅当

bar b;
foo f;
b(f);

会编译吗?我调查了各种相关问题(包括上面提到的)并尝试了

template<typename Func, typename Arg>
class has_call_with_arg
{
  struct bad {};
  struct test : Func
  {
    template<typename C>
    bad operator()(C const&r);
  };
public:
  static const bool value = 
    !std::is_same<bad, typename std::result_of<test(Arg const&)>::type >::value;
};

但这没有用(没有检测到正确的匹配项)。怎么了?

最佳答案

template<typename sig, typename functor> struct is_callable;
template<typename Ret, typename... Arg, typename functor> 
struct is_callable<Ret(Arg...), functor> { // partial spec
private:
    struct no {};
public:
    template<typename U> static auto f(std::nullptr_t) -> decltype(std::declval<U>()(std::declval<Arg>()...));
    template<typename U> static no f(...);
    static const int value = std::is_convertible<decltype(f<functor>(nullptr)), Ret>::value;
};

我创建了此内容 for my tutorials ,它解释了这个特征的构造(首先是非可变形式)。

关于c++ - 如何检查成员运算符(类型)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15163512/

相关文章:

c++ - 没有重载函数需要 2 个参数(仿函数)

templates - 使用表达式或类型名 (DLang) 调用的 D 模板

c++ - 标准中哪里说不允许声明 `auto f()() ->int;`?

c++ - 计算双C++中的位数

c++ - 访问负像素值 OpenCV

c++ - C++ 中的 std::map 内部是什么数据结构?

c++ - 静态数组的行为改变了吗?

templates - 如何在 MediaWiki 中隐藏侧边栏?

c++ - 概念检查器无法在 gcc 上编译,因为它是 'has no linkage'

c++ - constexpr 适用于 Ubuntu,但不适用于 MacOS