检测模板化方法和自由函数的存在
Detect presence of templated methods and free functions
我有一组专门的模板。现在我想为两种情况创建专门的模板:
-
如果某个方法存在于类/结构中(检测名称就足够了)。
-
如果存在某个自由函数(在这种情况下,应该检测名称和签名的一部分)。
问题是,自由函数和类方法也将被模板化。这是一种序列化体系结构,我有多种序列化方式,因此方法/函数的模板参数将是由专门的其他模板提供的序列化策略。我不能将该策略作为一个抽象的基础,因为稍后将调用其他模板化方法,并且虚拟和模板不会混合。
这里有一个我需要的例子:
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的检测,但宏仍然需要,因为你需要一种提取成员名称的方法。
相关文章:
- 将自由函数绑定为类成员函数
- 如何将成员函数作为回调参数传递给需要"typedef-ed"自由函数指针的函数?
- 为什么成员函数地址离自由函数这么远?
- 如何使用模板元编程在自由函数C++链接两个不相关的类
- C++ 20 中的运算符 == 和 <=> 应该作为成员还是自由函数实现?
- 如何在共享库中保留静态库中的自由函数
- 在C++项目中管理自由函数有哪些好的做法?
- 使用自由函数作为LPOVELAPPED_COMPLETION_ROUTINE
- 统一检查成员函数、自由函数和算子是否存在的方式
- 使自由函数的行为类似于成员函数 (C++)
- C++自由函数可以别名吗?
- 调用成员函数(如果存在),回退到自由函数,反之亦然
- ADL找不到模板化的自由函数
- 基于方法或自由函数存在的模板构造函数解析
- G 未定义的引用自由函数
- 为什么未调用自由函数作为构造函数中的参数传递
- 自由函数和继承
- 调用自由函数而不是方法(如果不存在)
- 如何将自由函数与对象一起使用
- 如何使用begin()自由函数