C++ literal type

要区分 literal 和 literal-type这两个不同的概念。

literal:文字量,10,3.14, true ,u8"123",  L"好"这些东西。

literal-type: 参考http://en.cppreference.com/w/cpp/concept/LiteralType  简单的说,就可以在用于编译期运算的对象。

对于标量,例如int,显然可以参与编译期运算,例如:constexpr int fac( int N);  //计算阶乘。所以标量都是属于literal-type。

从这里可以看出,literal-type仅仅是类型系统中,一个catalog。所有的类型,要么归类到literal-type,要么归类到none-literal-type。

现在class,也能归类于literal-type,只要满足一些条件:

 1 struct point 
 2 {
 3     point(): x(0), y(0){  std::cout << "point() called" << std::endl; }
 4     constexpr point(int x_, int y_): x(x_),y(y_){}
 5     constexpr int hypot() { return x*x + y*y; }
 6     
 7 private:
 8     int x,y;
 9 };
10  
11 int main()
12 {   
13     static_assert( point(3,4).hypot() == 25 );
14     std::cout << "std::is_literal_type<point>::value=" << std::is_literal_type<point>::value;
15 }

point符合literal定义。可以参与到编译期运算static_assert。下面举个反例:

1 struct point 
2 {
3     point(): x(0), y(0){  std::cout << "point() called" << std::endl; }
4     constexpr point(int x_, int y_): x(x_),y(y_){}
5     constexpr int hypot() { return x*x + y*y; }
6     ~point(){} 
7     int x,y;
8 };

第6行,加了析构函数,point就不再是literal-type了。

1 struct point 
2 {
3     point(): x(0), y(0){  std::cout << "point() called" << std::endl; }
4     point(int x_, int y_): x(x_),y(y_){}
5     constexpr int hypot() { return x*x + y*y; }
6 private:
7     int x,y;
8 };

第6行,加了private,point就不再是aggregate-type; 并且构造函数去了constexpr。point就不是literal-type.

改造一下:

struct point 
{
    point(): x(0), y(0){  std::cout << "point() called" << std::endl; }
    constexpr point(int x_, int y_): x(x_),y(y_){}
    constexpr int hypot() { return x*x + y*y; }
private:
    int x,y;
};

现在这个none-aggregate-type就是literal-type

 

原文链接: https://www.cnblogs.com/thomas76/p/8646036.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    C++ literal type

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/397532

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年4月11日 上午9:14
下一篇 2023年4月11日 上午9:14

相关推荐