You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++11中如何从可转换为B<C>的TMethod提取C类型?

在C++11中从可转换为B的TMethod提取C类型

要从可转换为B<C>的模板参数TMethod中提取C类型,你可以借助类型推导辅助函数结合decltype实现,具体步骤如下:

1. 定义类型推导辅助函数

先在函数外部(类A内部或全局作用域)声明一个仅用于类型推导的辅助函数模板(无需实现,我们只需要它的类型信息):

// 仅用于类型推导,无需编写函数体
template<typename C>
C extractC(B<C>);

这个函数的作用是:当传入B<C>类型参数时,返回值类型就是我们需要的C。

2. 在calledMethod中提取C类型

在目标函数里,利用decltype和std::declval触发类型推导,得到C类型:

#include <utility> // 引入std::declval

template<typename TMethod, typename... Args>
decltype(auto) calledMethod(const Member<TMethod>& method)
{ 
    // 提取出C类型
    using C = decltype(extractC(std::declval<TMethod>()));
    
    // 现在可以正常访问C的成员
    C::Output dummy;
    return dummy;
}

原理说明

  • std::declval<TMethod>()会生成一个TMethod类型的右值引用,模拟可转换为B<C>的对象。
  • 由于TMethod可转换为B<C>,编译器会自动匹配到extractC(B<C>)重载,推导模板参数C的具体类型。
  • decltype(extractC(...))会捕获推导后的C类型,通过using定义为可用的类型别名。

内容的提问来源于stack exchange,提问作者Justplayit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 02:31:19