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

C模板元编程:如何推断表达模式中的类型

发布时间:2020-12-16 07:22:32 所属栏目:百科 来源:网络整理
导读:我想要一个lambda参数类型的静态检查.我在下面编写了这段代码,似乎产生了正确的结果. struct B { };auto lamBc = [](B const b) { std::cout "lambda B const" std::endl; };templatetypename ClosureType,typename R,typename Argconstexpr auto ArgType(R
我想要一个lambda参数类型的静态检查.我在下面编写了这段代码,似乎产生了正确的结果.

struct B { };
auto lamBc = [](B const& b) { std::cout << "lambda B const" << std::endl; };

template<typename ClosureType,typename R,typename Arg>
constexpr auto ArgType(R (ClosureType::*)(Arg) const)->Arg;

template <typename T>
using ArgType_t = decltype(ArgType(&T::operator()));

// ArgType_t<lamBc> is "reference to B const"

但是,我注意到,例如,标准库使用类模板特化来从std :: remove_reference中的引用类型中提取引用类型.所以我尝试了这种方法,它似乎也产生了正确的结果.

template<typename L>
struct ArgType2;

template<typename ClosureType,typename Arg>
struct ArgType2<R (ClosureType::*)(Arg) const>
{
    typedef Arg type;
};

template <typename T>
using ArgType2_t = typename ArgType2<decltype(&T::operator())>::type;

// ArgType2_t<lamBc> is also "reference to B const"

我的问题是:哪种是从模式表达式中提取类型的标准方法?两种方法的权衡取舍是什么?

解决方法

您的方法都是有效的,可互换的并且导致相同的结果(推断出lambda接受的参数的类型).

对于类型特征,标准要求(见23.15.1要求):

  1. A UnaryTypeTrait describes a property of a type. It shall be a class template that takes one template type argument and,optionally,additional arguments that help define the property being described. …

  2. A BinaryTypeTrait describes a relationship between two types. It shall be a class template that takes two template type arguments
    and,additional arguments that help define the
    relationship being described. …

  3. A TransformationTrait modifies a property of a type. It shall be a class template that takes one template type argument and,additional arguments that help define the modification. …

我认为这个要求主要出于历史原因出现,因为在提出类型特征之后引入了decltype功能(并且这些类型特征基于来自boost的类型特征,甚至更早创建,参见this).

另外,请注意,类模板对于通用类型特征比基于函数声明和decltype的逻辑更灵活.

重点是在C 11及更高版本的特定情况下,您可以自由使用最方便的方式,更好地反映编程逻辑.

(编辑:李大同)

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

    推荐文章
      热点阅读