C++11 元编程 : check for method existence

标签 c++ templates c++11 sfinae

<分区>

1) 我有两个类(class) class Aclass B两者都有一个名为 foo 的方法但具有不同的参数列表。

class A {
public:
  void foo(int a);
};

class B {
public:
  void foo(int a, int b);
};

2) 此外,我有一个 class C使用模板参数 T还有一个 foo方法如下

template <typename T>
class C {
public:
  void foo();
private:
  T t_;
  int a_;
  int b_;
};

3) 我想同时使用 class Aclass B作为 class C 的模板参数. 说我想要一个方法 C::foo实现如下:

template <typename T>
void C<T>::foo()
{
  if (compile time check: T has foo(int a, int b))
   t_.foo(a_, b_);
  else
   t_.foo(a_);
}

如何表达 if上面的声明 C++11

最佳答案

使用SFINAE (使用函数模板重载)。

template <typename T>
class C {
private:
    T t_;
    int a_;
    int b_;
public:
    template <typename X = T>
    auto foo() -> decltype (std::declval<X>().foo(a_)) {
        t_.foo(a_);
    }
    template <typename X = T>
    auto foo() -> decltype (std::declval<X>().foo(a_, b_)) {
        t_.foo(a_, b_);
    }
};

LIVE

关于C++11 元编程 : check for method existence,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39387048/

相关文章:

c++ - 使用另一个模板类的嵌套名称说明符专门化一个模板类

c++ - 带有返回 const 引用的隐式转换运算符的类的 static_cast<> 行为

c++ - Macports GCC 4.8 无法链接 OSX Lion 上的 c++ 库

c++ - VSTest.console 按属性筛选 native c++ 单元测试

c++ - 无法使用 boost asio 专门绑定(bind)到网络端口

javascript - meteor :在单独的列表标签中显示 mongo 数组中的每个项目

c++ - 无法将函数定义与模板化类中的现有定义相匹配

c++ - 调用模板参数 constexpr 方法?

c++ - Ifstream 从文本文件中读取错误的字符

c++ - openmp 共享或什么都没有。私有(private)与未初始化