检测模板化方法和自由函数的存在

Detect presence of templated methods and free functions

本文关键字:自由 函数 存在 方法 检测      更新时间:2023-10-16

我有一组专门的模板。现在我想为两种情况创建专门的模板:

  1. 如果某个方法存在于类/结构中(检测名称就足够了)。

  2. 如果存在某个自由函数(在这种情况下,应该检测名称和签名的一部分)。

问题是,自由函数和类方法也将被模板化。这是一种序列化体系结构,我有多种序列化方式,因此方法/函数的模板参数将是由专门的其他模板提供的序列化策略。我不能将该策略作为一个抽象的基础,因为稍后将调用其他模板化方法,并且虚拟和模板不会混合。

这里有一个我需要的例子:

template<typename T>
struct strategy1 {};
template<>
struct strategy1<char> {
  void call() {
    // Do char specific stuff
  }
};
class foo_specialized {
/* ... */
};
template<>
struct strategy1<foo_specialized> {
  void call() {
    // do foo_specialized stuff
  }
};
class foo_method {
public:
  template< Typename T>
  void serialize( T & t ) {
    // use T here to do stuff
  }
};
/* This should be used for foo_method */
template< typename T >
struct strategy1</* don't know what to put here */>
  struct strategy1_helper{
    template<typename T2>
    void call( T2 t ) {
       // do stuff with t
    }
   };
  void call( const T & t ) {
    t.serialize( strategy1_helper() );
  } 
};
class foo_function {
/* ... */
};
template<typename T>
void serialize( const foo_function & foo, T & t ) {
  // use T here
}
/* This should be used for foo_function */
template< typename T >
struct strategy1</* don't know what to put here */>
  struct strategy1_helper{
    template<typename T2>
    void call( T2 t ) {
       // do stuff with t
    }
   };
  void call( const T & t ) {
    serialize( t, strategy1_helper() );
  } 
};

是否有可能让模板解决机制根据实际提供的论点选择这两个最后的专业化?或者有没有更干净的设计来实现这一点?

我可以很容易地使用C++11提供的类型特征和元编程工具,所以我不必自己完成SFINAE步骤。

该解决方案需要使用SFINAE来检测所述成员函数的潜在返回类型。该技巧在访问成员指针失败的情况下使用省略号重载。

正确的实现也需要一些宏样板。我有这样一个实现:

https://github.com/jfalcou/boosties/tree/master/introspection/boost

现在,用C++11的思维方式,其中一些当然可以变成基于decltype的检测,但宏仍然需要,因为你需要一种提取成员名称的方法。