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

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

概述我想要一个lambda参数类型的静态检查.我在下面编写了这段代码,似乎产生了正确的结果. struct B { };auto lamBc = [](B const& b) { std::cout << "lambda B const" << std::endl; };template<typename ClosureType, typename R, typename Arg>conste 我想要一个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要求):

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. …

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. …

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及更高版本的特定情况下,您可以自由使用最方便的方式,更好地反映编程逻辑.

总结

以上是内存溢出为你收集整理的C模板元编程:如何推断表达模式中的类型全部内容,希望文章能够帮你解决C模板元编程:如何推断表达模式中的类型所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1229036.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-05
下一篇 2022-06-05

发表评论

登录后才能评论

评论列表(0条)

保存