yo_*_*gdg 3 c++ winapi templates template-meta-programming c++14
我正在为Win32的SQL ODBC API开发一个包装器,并且经常有几个函数像GetXXXTextA和GetXXXTextW.我打算选择合适的GetA或GetW取决于用户输入类型.我试过这个:
// test getterA
int _stdcall pruebaA (int, char*, const char*)
{ return 0; }
// test getterW
int _stdcall pruebaW(int, wchar_t*, const wchar_t*)
{ return 0; }
template<typename T>
struct only_char_or_wchar_t
{
using ct = std::enable_if_t<std::is_same<T, char>::value || std::is_same<T, wchar_t>::value, T>;
};
template<typename char_type> struct char_or_wchart_api: only_char_or_wchar_t<char_type>
{
constexpr static std::conditional_t<std::is_same<char_type, wchar_t>::value, int (_stdcall*)(int, wchar_t*, const wchar_t*) , int(_stdcall*)(int, char*, const char*)> prueba =
std::is_same<char_type, wchar_t>::value
?
::pruebaW :
::pruebaA;
};
int main () {
auto p2 = char_or_wchart_api<wchar_t>::prueba;
p2(0, nullptr, L"");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但是,Visual Studio 2017一直在抱怨(在线" ::pruebaA;"):
Error C2446: ':': no conversion from 'int (__stdcall *)(int,char *,const char *)' to 'int (__stdcall *)(int,wchar_t *,const wchar_t *)'
尽管智能感知解析正确时,"呼唤" p2(.....) ,以(int, wchar_t*, const wchar_t*)
你知道这段代码有什么问题吗?
请注意pruebaA并pruebaW具有不同的类型:
int _stdcall pruebaA(int, char*, const char*)
int _stdcall pruebaW(int, wchar_t*, const wchar_t*)
Run Code Online (Sandbox Code Playgroud)
第一个函数从第二个函数采用不同的参数类型,因此两个函数类型是不兼容的.您不能从三元组返回指向它们的指针,因为三元组中的两种类型都必须兼容.
但是,你太复杂了.只需编写一个重载函数:
// Choose better names for the arguments
int prueba(int arg1, char* arg2, const char* arg3) {
return pruebaA(arg1, arg2, arg3);
}
int prueba(int arg1, wchar_t* arg2, const wchar_t* arg3) {
return pruebaW(arg1, arg2, arg3);
}
Run Code Online (Sandbox Code Playgroud)
这也简化了用法,因为您只需要编写prueba(0, nullptr, L""),而不必指定要调用的函数.