c ++ 11元编程:检查方法是否存在

Tru*_*uLa 2 c++ templates sfinae c++11

1)我有两个类class A,class B它们都有一个被调用foo但有不同参数列表的方法.

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

class B {
public:
  void foo(int a, int b);
};
Run Code Online (Sandbox Code Playgroud)

2)此外,我有一个class Cwith template参数T,它也有一个foo方法如下

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

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_);
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能表达上述if陈述C++11

son*_*yao 6

使用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_);
    }
};
Run Code Online (Sandbox Code Playgroud)

生活

  • 旁注:如果`T`同时具有两种方法(模糊调用),则不再有效. (3认同)