加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C模板元功能

发布时间:2020-12-16 10:37:51 所属栏目:百科 来源:网络整理
导读:我正在为Win32的SQL ODBC API开发一个包装器,并且常常有几个函数,如GetXXXTextA和GetXXXTextW.我根据用户输入类型选择合适的GetA或GetW.我试过这个: // test getterAint _stdcall pruebaA (int,char*,const char*){ return 0; }// test getterWint _stdcall
我正在为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,int (_stdcall*)(int,const wchar_t*),int(_stdcall*)(int,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 *)’

当“调用”p2(…..)到(int,const wchar_t *)时,intellisense正确解析

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

解决方法

正如Klaus(和Justin,和R Sahu)所解释的那样,你的三元运算符会收到两个不兼容的对象.

但是,如果你使用模板特化,你不需要only_char_or_wchar_t和(可能使用auto类型)都变得更简单了

template <typename>
struct char_or_wchart_api;

template <>
struct char_or_wchart_api<char>
 { static constexpr auto prueba = ::pruebaA; };

template <>
struct char_or_wchart_api<wchar_t>
 { static constexpr auto prueba = ::pruebaW; };

但是更好的解决方案(恕我直言)是Justin(和Klaus,第(2)点)提出的解决方案:两个具有相同名称的函数;选择正确的参数.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读