问题描述
我要求一个模板技巧来检测类是否具有给定签名的特定成员函数。
I'm asking for a template trick to detect if a class has a specific member function of a given signature.
问题与此处引用的问题类似
,但不一样:在Sutter的书中,他回答了一个问题:类C必须提供一个带有特定签名的成员函数,否则程序不会编译。在我的问题,我需要做一些事情,如果一个类有该函数,否则做别的东西。
The problem is similar to the one cited herehttp://www.gotw.ca/gotw/071.htmbut not the same: in the item of Sutter's book he answered to the question that a class C MUST PROVIDE a member function with a particular signature, else the program won't compile. In my problem I need to do something if a class has that function, else do "something else".
boost :: serialization遇到类似的问题,但我不喜欢他们采用的解决方案:一个模板函数,默认调用一个自由函数定义)特定的签名,除非你定义一个特定的成员函数(在他们的情况下,serialize有一个给定的类型的2个参数),否则会发生编译错误。这就是实现侵入和非侵入序列化。
A similar problem was faced by boost::serialization but I don't like the solution they adopted: a template function that invokes by default a free function (that you have to define) with a particular signature unless you define a particular member function (in their case "serialize" that takes 2 parameters of a given type) with a particular signature, else a compile error will happens. That is to implement both intrusive and non-intrusive serialization.
我不喜欢这个解决方案有两个原因:
I don't like that solution for two reasons:
- 非侵入性的,你必须重写boost :: serialization命名空间中的全局serialize函数,所以你有你的客户代码打开命名空间boost和命名空间序列化!
-
mess是10到12个函数调用。
我需要为没有该成员的类定义一个自定义行为函数,我的实体位于不同的命名空间中(当我在另一个命名空间中时,我不想覆盖一个命名空间中定义的全局函数)
I need to define a custom behavior for classes that has not that member function, and my entities are inside different namespaces (and I don't want to override a global function defined in one namespace while I'm in another one)
给我一个提示来解决这个难题?
Can you give me an hint to solve this puzzle?
推荐答案
我不知道我是否理解你正确,但你可能利用SFINAE以在编译时检测功能存在。示例从我的代码(测试类是否有成员函数size_t used_memory()const)。
I'm not sure if I understand you correctly, but you may exploit SFINAE to detect function presence at compile-time. Example from my code (tests if class has member function size_t used_memory() const).
template<typename T>
struct HasUsedMemoryMethod
{
template<typename U, size_t (U::*)() const> struct SFINAE {};
template<typename U> static char Test(SFINAE<U, &U::used_memory>*);
template<typename U> static int Test(...);
static const bool Has = sizeof(Test<T>(0)) == sizeof(char);
};
template<typename TMap>
void ReportMemUsage(const TMap& m, std::true_type)
{
// We may call used_memory() on m here.
}
template<typename TMap>
void ReportMemUsage(const TMap&, std::false_type)
{
}
template<typename TMap>
void ReportMemUsage(const TMap& m)
{
ReportMemUsage(m,
std::integral_constant<bool, HasUsedMemoryMethod<TMap>::Has>());
}
这篇关于检查类是否具有给定签名的成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!