如果存在的话就调用

Posted abelian

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如果存在的话就调用相关的知识,希望对你有一定的参考价值。

一,判断在类中某个函数(也可以是变量或类型)是否存在
template<typename T>
struct xxxx_detector
{
    template<typename P,void (P::*)(void)> struct detector{};
    template<typename P> static char func(detector<P,&P::init>*);
    template<typename P> static long func(...);
    static constexpr bool value  = sizeof(func<T>(nullptr)) == sizeof(char);
};
这样的话xxxx_detector<YYY>::value,当类型YYY存在成员函数void YYY::init(void),这个值就是true。
如果存在的话就调用
template<bool> 
struct either_or
{
    template<typename T,typename K,typename ...AK> 
    auto operator()(T&& t, K&& k, AK&&... ak)
    {
      return t(ak...);
    }
};
template<> 
struct either_or<false>
{
    template<typename T,typename K,typename ...AK> 
    auto operator()(T&& t,K&& k,AK&&... ak)
    {
      return k(ak...);
    }
};
这样的话,只要使用
either_or<xxxx_detector<YYY> >(
[](auto&& i)  // 第一个参数
 {
  i.init();
 },
[](auto&& i) //第二个参数
{},
 YYY()    // 第三个参数
),
如果存在就调用,不存在就啥都不干。

以上是关于如果存在的话就调用的主要内容,如果未能解决你的问题,请参考以下文章