gpt4 book ai didi

C++ 模板元函数

转载 作者:太空狗 更新时间:2023-10-29 19:43:03 24 4
gpt4 key购买 nike

我正在为 Win32 开发 SQL ODBC API 的包装器,并且经常有几个函数,如 GetXXXTextAGetXXXTextW。我要根据用户输入类型选择适当的 GetAGetW。我试过这个:

// 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;
}

但是,Visual Studio 2017 一直在提示(在“::pruebaA;”行):

错误 C2446:“:”:没有从“int (__stdcall *)(int,char *,const char *)”到“int (__stdcall *)(int,wchar_t *,const wchar_t *)”的转换'

即使 intellisense 在“调用”p2(.....)(int, wchar_t*, const wchar_t*) 时正确解析

你知道这段代码可能有什么问题吗?

最佳答案

注意 pruebaApruebaW 有不同的类型:

int _stdcall pruebaA(int, char*, const char*)
int _stdcall pruebaW(int, wchar_t*, const wchar_t*)

第一个函数采用与第二个函数不同的参数类型,因此这两种函数类型不兼容。您不能从三元返回指向它们的指针,因为三元中的两种类型必须兼容。


但是,您将其复杂化了。只需编写一个重载函数:

// 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);
}

这也简化了用法,因为您只需编写 prueba(0, nullptr, L""),而不必指定要调用的函数。

关于C++ 模板元函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49638182/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com