Effective C++: constexpr(during compilation).

注意: constexpr只能用於字面值類型(literal type),  string.ios

用戶自定義類型(user-defined),IO庫都是不行的.ui

字面值類型通常是數字,字符,或者雙引號內的字符串, 可是咱們也能夠本身定義字面值類型(literal type).this

好吧讓咱們來看代碼吧!spa

 #include <iostream>
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<<counter(1, 2)<<std::endl;  //運行時纔出來結果.
 constexpr int number = counter(2, 3); //編譯時期(during compilation),就已經獲得了number的結果.
 //注意這裏的2, 3的效果其實和 consexpr int n3=2; constexpr int n4=3;效果一致的. 
 
 constexpr auto n = counter(1, 2);     //也是編譯時期得到結果. 
 int n2 = counter(1, 3);               //運行(run-time)時才獲得n2的結果. 
 std::cout<<number<<std::endl; 
 
 constexpr Point p1(9.4, 8.3);
 constexpr Point p2(5.5, 6.6);
 
 Point p3 = midPoint(p1, p2); //運行時才得出p3。
 constexpr Point p4 = midPoint(p1, p2); //編譯器就獲得了p4. 
 constexpr Point p5 = midPoint(Point(1, 2), Point(3, 4)); //編譯時期獲得p5. 
 
 
 return 0;
}

再來看一個Demo咱們如何自定義(literal type):code

#include <iostream>
#include <stdexcept>
 
class conststr
{
    const char* p;
    std::size_t sz;
public:
    template<std::size_t N>
    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 testing
template<int n>
struct constN
{
    constN() { std::cout << n << '\n'; }
};
 
int main()
{
    std::cout << "the number of lowercase letters in \"Hello, world!\" is ";
    constN<countlower("Hello, world!")>(); // implicitly converted to conststr
}
相關文章
相關標籤/搜索