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

c++11 metaprogramming: check for method existence

本文关键字:方法 是否 存在 检查 编程 c++11      更新时间:2023-10-16

1)我有两个类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_);
}

如何在C++11中表达上面的if语句

使用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_);
    }
};
生活

如果你知道哪种类型包含void foo(int a, int b);在这种情况下,你可以使用模板特化,比如

template <typename T>
class C
{
private:
  T t_;
  int a_;
  int b_;
public:
    // called for general use
    void foo()
    {
        t_.foo(a_);
    }
};
// specialized version for T = B
template<> 
void C<B>::foo()
{
    t_.foo(a_, b_);
}