功能指针的功能模板专业化 [英] Function Template Specialization on Function Pointers

查看:72
本文介绍了功能指针的功能模板专业化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个清理功能,只想在(传统)指针类型上运行.

I have a sanitization function that I want to run on (traditional) pointer types only.

我的问题是函数模板,我只能将函数限制为仅指针,但是由于函数指针和常规指针之间的转换规则不同,我遇到了问题.

My problem is with function templates I can get as far as limiting the function to only pointers, however because of casting rule differences between function pointers and regular pointers, I run into problems.

Sanitize()函数需要针对一整套类型运行,其中一些是指针,需要进行清理,其中一些是具有不同Arity和参数类型的函数指针,不应对其进行清理,其中一些属于非指针数据类型,也不应进行清理.

The Sanitize() function needs to run against a whole slew of types, some of which are pointers and need to be sanitized, others of which are function pointers of varying arity and parameter types and should not be sanitized, and some of which are non-pointer data types which also should not be sanitized.

有什么明显的我想念吗?

Anything obvious I'm missing?

  template<typename T>
  T* Sanitize(T* value)
  {
     return (T*)SanitizePointer(value);  //SanitizePointer returns void*, so cast is necessary
  }

  template<typename T>
  T Sanitize(T value)
  {
     return value;  //Non-pointers can be passed without sanitization
  }

  int main()
  {

     int  a;
     int* b;
     int (*c)();

     Sanitize(a);
     Sanitize(b);
     Sanitize(c);   //<- ERROR

     return 0;
  }

推荐答案

虽然可以手动解决此问题,但最容易利用Boosts类型特征和

While this problem could be solved manually, its easiest to utilize Boosts type traits and SFINAE helper to selectively disable the overload for pointers if T* is a function pointer:

template<typename T>
typename boost::disable_if<boost::is_function<T>, T*>::type
Sanitize(T* value)
{
    // ...
}

这篇关于功能指针的功能模板专业化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆