首页 > 代码库 > [c++] constexpr and literal class

[c++] constexpr and literal class

稀奇古怪的新特性,菜鸟在此啄上一啄。

 

1. 

When should literal classes be used in C++?

 
2.
int i; // not constantconst int size = i; // fine! 可以,但为什么不在这里就先判断出问题的隐患呢?int arr[size]; // Error!
然而对于constexpr,则表明这个值不仅是constant的,而且也是编译期确定的
int i; // not constantconstexpr int size = i; // Error!

于是,constexpr修饰的变量是可以表示数组大小的。
 
放在 stack上的数组也是可以的,比如main中的如下:
int main(){   int i;   cin >> i;   int arr[i];}

跟const无关,而是使用了C99的一个特性,名叫variable length array(简称VLA)。

而为什么我们需要constexpr呢?那就是为了性能。

 

3.

Want speed? Use constexpr meta-programming!

static的方式是最快的。

 

4. 

When should you use constexpr capability in C++11?

Suppose it does something a little more complicated.

constexpr int MeaningOfLife ( int a, int b ) { return a * b; }const int meaningOfLife = MeaningOfLife( 6, 7 );

使用组合!

Now you have something that can be evaluated down to a constant while maintaining good readability and allowing slightly more complex processing than just setting a constant to a number.

It basically provides a good aid to maintainability as it becomes more obvious what you are doing. Take max( a, b ) for example:

template< typename Type > constexpr Type max( Type a, Type b ) { return a < b ? b : a; }

替代模板计算的一个很好的方式!效率比模板高。

 

 

 


Literal Type 



down voteaccepted

The defintion of "literal type" is in [basic.types] (C++11 3.9):

A type is a literal type if it is:

  • void; or
  • a scalar type; or
  • a reference type; or
  • an array of literal type; or
  • a class type (Clause 9) that has all of the following properties:
  • it has a trivial destructor,
  • it is an aggregate type (8.5.1) or has at least one constexpr constructor or constructor template that is not a copy or move constructor, and
  • all of its non-static data members and base classes are of non-volatile literal types.

Literal types are broadly speaking the types that are permitted to occur as and in constant expressions.

There is a trait, std::is_literal_type, for checking if a type is a literal type.

 是否是literal type?

// is_literal_type example#include <iostream>#include <type_traits>struct A { };struct B { ~B(){} };int main() {  std::cout << std::boolalpha;  std::cout << "is_literal_type:" << std::endl;  std::cout << "int: " << std::is_literal_type<int>::value << std::endl;  std::cout << "int&: " << std::is_literal_type<int&>::value << std::endl;  std::cout << "int*: " << std::is_literal_type<int*>::value << std::endl;  std::cout << "A: " << std::is_literal_type<A>::value << std::endl;  std::cout << "B: " << std::is_literal_type<B>::value << std::endl;  return 0;}

Output:

is_literal_type:int: trueint&: trueint*: trueA: trueB: false

 


 

一些问题:

constexpr vs template for compile-time maths functions?

元编程

泛型编程

 

continue...

[c++] constexpr and literal class