问题
I stumbled on a strange phenomenon while developping a templated API for accessing the windows registry.
I thought I was smart by 'capturing' the ascii and unicode versions of the windows API in static constexpr 'variabeles' of 2 t_api structs ( t_api_A and t_api_W ).
Everything was compiling fine ,but running not so much (exceptions on calling the 'captured functions'). So I used a piece of code (from Scott Meyers' book "Effective Modern C++") to see the deducted types. Apparently if I place those 'function captures' in structs it doesn't work ,however a simple auto = ...; inside a function does.
Clearly I'm doing something wrong ,but I can't see why my approach is faulty.
Here's the code (some code is commented out because they purposefully generate errors)
#include<Windows.h>
//==============================================================================
namespace wreg {
//------------------------------------------------------------------------------
using t_oshandle = HKEY;
struct t_api
{
static constexpr
auto open_key = ::RegOpenKeyExA;
// Tried all of these :
// RegOpenKeyExA; &RegOpenKeyExA; (::RegOpenKeyExA); (RegOpenKeyExA); (&RegOpenKeyExA);
//
static
constexpr auto close_key = ::RegCloseKey;
};
//------------------------------------------------------------------------------
} // namespace wreg
//==============================================================================
template < typename T >
struct type_deduced; // see Scott Meyers' "Effective Modern C++"
#define TYPE_DEDUCED( nr , t ) type_deduced< t > dummy_ ## nr
int main ()
{
//type_deduced< decltype(RegOpenKeyExA) > s1;
//TYPE_DEDUCED( 1 , decltype(RegOpenKeyExA) ); // 'dummy_1' uses undefined struct 'type_deduced<LSTATUS (HKEY,LPCSTR,DWORD,REGSAM,PHKEY)>'
//TYPE_DEDUCED( 1a , decltype(::RegOpenKeyExA) ); // 'dummy_1a' uses undefined struct 'type_deduced<LSTATUS (HKEY,LPCSTR,DWORD,REGSAM,PHKEY)>'
//TYPE_DEDUCED( 3 , decltype(wreg::t_api::open_key) ); // 'dummy_3' uses undefined struct 'type_deduced<LSTATUS (__stdcall *const )(HKEY,LPCSTR,DWORD,REGSAM,PHKEY)>'
auto hk = wreg::t_oshandle{};
#define ORIGINAL_APPROACH 0
#ifdef ORIGINAL_APPROACH // faulty version
auto res = wreg::t_api::open_key( HKEY_LOCAL_MACHINE ,"SOFTWARE" ,0 ,KEY_READ ,&hk );
if (res == ERROR_SUCCESS)
{
res = wreg::t_api::close_key( hk );
}
#else // working version
auto open_key = ::RegOpenKeyExA;
auto res = open_key( HKEY_LOCAL_MACHINE ,"SOFTWARE" ,0 ,KEY_READ ,&hk );
if (res == ERROR_SUCCESS)
{
auto close_key = ::RegCloseKey;
res = close_key( hk );
}
#endif
return 0;
}
//==============================================================================
回答1:
Bug is resolved in VS 2015 RTM.
来源:https://stackoverflow.com/questions/30519363/wrong-type-deduction-of-function-signature