首页 > 解决方案 > 如何在不使用 const_cast 的情况下打开 HINSTANCE?

问题描述

标题已经说了。

见真实世界的例子见:https ://docs.microsoft.com/en-us/windows/desktop/api/shellapi/nf-shellapi-findexecutablea

这将返回一个 HINSTANCE - 它是一种指针类型 - 在某些情况下可以假定预定义的错误值。

最好是,我想打开一个 HINSTANCE 并在不求助于const_cast或 c 风格的演员的情况下做到这一点——这如何实现?

示例代码:

bool test_result(const HINSTANCE ptr) {
  switch (ptr) {
  case 2 /*SE_ERR_FNF*/:
    return false;
  default:
    return true;
  }
}

标签: c++castingswitch-statementc++17

解决方案


用于将指针(HINSTANCE 只是一个 void*)转换为 int 你reinterpret_castuintptr_t. 像这样:

bool test_result(const HINSTANCE ptr)
{
  switch (reinterpret_cast<uintptr_t>(ptr))
  {
  case 2 /*SE_ERR_FNF*/:
    return false;
  default:
    return true;
  }
}

推荐阅读