博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Effective C++: constexpr(during compilation).
阅读量:6909 次
发布时间:2019-06-27

本文共 1882 字,大约阅读时间需要 6 分钟。

hot3.png

注意: constexpr只能用于字面值类型(literal type),  string.

用户自定义类型(user-defined),IO库都是不行的.

字面值类型一般是数字,字符,或者双引号内的字符串, 但是我们也可以自己定义字面值类型(literal type).

好吧让我们来看代码吧!

 #include 
constexpr int counter(const int& a, const int& b)noexcept { return a + b;}
class Point{ private:  double x;  double y;    public:   constexpr Point(const double& xVal =0, const double& yVal = 0):x(xVal),y(yVal){}      ~Point()=default;      constexpr const double& xValue()const noexcept {return this->x;}   constexpr const double& yValue()const noexcept {return this->y;}      void setX(const double& xVal)noexcept {this->x = xVal;}   void setY(const double& yVal)noexcept {this->y = yVal;}};
constexpr Point midPoint(const Point& lp, const Point& rp)noexcept{ return Point(lp.xValue()+2, rp.yValue()+2);}
int main(){ std::cout<
<

再来看一个Demo我们如何自定义(literal type):

#include 
#include
class conststr{ const char* p; std::size_t sz;public: template
constexpr conststr(const char(&a)[N]) : p(a), sz(N - 1) {} constexpr char operator[](std::size_t n) const { return n < sz ? p[n] : throw std::out_of_range(""); } constexpr std::size_t size() const { return sz; }}; constexpr std::size_t countlower(conststr s, std::size_t n = 0, std::size_t c = 0){ return n == s.size() ? c : s[n] >= 'a' && s[n] <= 'z' ? countlower(s, n + 1, c + 1) : countlower(s, n + 1, c);} // output function that requires a compile-time constant, for testingtemplate
struct constN{ constN() { std::cout << n << '\n'; }}; int main(){ std::cout << "the number of lowercase letters in \"Hello, world!\" is "; constN
(); // implicitly converted to conststr}

 

转载于:https://my.oschina.net/SHIHUAMarryMe/blog/659266

你可能感兴趣的文章
每日练习
查看>>
LeetCode算法题-First Unique Character in a String(Java实现)
查看>>
【小程序】小程序开发自定义组件的步骤>>>>>>>>>小程序开发过程中报错:jsEnginScriptError...
查看>>
OSI模型
查看>>
用Quick Cocos2dx做一个连连看(三)
查看>>
好久没做.Net开发了,今天配置IIS和.Net Framework 4.0遇到点问题
查看>>
emoji情感分类器
查看>>
简单理解java反射机制
查看>>
Codeforces 399B - Red and Blue Balls
查看>>
实验五
查看>>
Qt资源
查看>>
n个骰子的点数
查看>>
Linux硬盘扩容(非LVM)
查看>>
glibc malloc常驻内存不释放问题抽象
查看>>
insufficient space
查看>>
linux获取CPU温度
查看>>
linux c 链接详解2-定义和声明
查看>>
负载均衡(Load Balancing)学习笔记(三)
查看>>
「一本通 1.1 练习 1」数列极差
查看>>
Event Flow
查看>>