【发布时间】:2018-08-05 04:45:39
【问题描述】:
我在编译时 c++ 计算过程中多次遇到这些术语。我已经在网上搜索了我无法理解的“专家级别”的资源。请帮助理解这些术语吗?我正在寻找初学者级别的好解释。 非常感谢您的帮助! 普雷
【问题讨论】:
标签: templates compiler-construction c++14 programming-languages metaprogramming
我在编译时 c++ 计算过程中多次遇到这些术语。我已经在网上搜索了我无法理解的“专家级别”的资源。请帮助理解这些术语吗?我正在寻找初学者级别的好解释。 非常感谢您的帮助! 普雷
【问题讨论】:
标签: templates compiler-construction c++14 programming-languages metaprogramming
C++ 中的元函数是一种使用模板元编程表达编译时计算的方式——使用模板实例化和类型推导在编译时生成结果。
从根本上说,元函数是一个具有constexpr 成员(用于元函数返回值)或typedefs(用于元函数返回类型)的类模板。
该技术可以通过元函数is_same 来说明,它检查两个类型参数是否相同。一个可能的实现(来自cppreference.com)是
template<class T, class U>
struct is_same : std::false_type {};
template<class T>
struct is_same<T, T> : std::true_type {};
其中std::true_type 是一个辅助元函数,它有一个成员constexpr bool value = true(和false 代表false_type)。
通过实例化模板并读取包含结果的成员来调用元函数,例如表达式
is_same<int,int32_t>::value
如果 int 是 32 位,则计算为布尔值 true,否则计算为 false。
另一个例子,来自type_traits 是std::is_floating_point,它检查一个类型是否为浮点类型。它可以称为
is_floating_point<int>::value
标准库(大部分)的约定是元函数返回值具有成员value,元函数返回类型具有类型别名type。
类型返回元函数的一个示例是std::iterator_traits,它用于获取有关迭代器的信息。例如,给定一个迭代器类型Iter,可以通过
iterator_traits<Iter>::value_type
和迭代器类别(例如,ForwardIterator、RandomAccessIterator 等)与
iterator_traits<Iter>::iterator_category
编译时计算的一个例子是计算阶乘的元函数:
template <unsigned int N>
struct Fac{
static constexpr unsigned int value = N * Fac<N-1>::value;
};
template <>
struct Fac<0>{
static constexpr unsigned int value = 1;
};
同样,这个元函数被称为Fac<5>::value
元类是对 C++ 的提议补充,允许在代码中表达对(某种)类的约束,而不仅仅是使用约定和文档。
例如,“接口”通常用于描述具有
的类使用元类interface,可以编写
interface Example {
void Foo();
int Bar(int);
}
然后编译器将其实例化为类
class Example {
public:
virtual void Foo() =0;
virtual int Bar(int) =0;
virtual ~Foo() =default;
}
可以在fluentc++ 博客文章中找到元类提案的一个很好的摘要。综合来源Herb Sutter's blog post
【讨论】: