Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

static_assert ใน C++


static_assert เป็นฟังก์ชันที่เป็นประโยชน์สำหรับโปรแกรมเมอร์ในการพิมพ์ข้อผิดพลาดในหน้าจอหลังจากรวบรวมโปรแกรมโดยไม่ทำให้เอาต์พุตยุ่งเหยิงเกินไป

ก่อนหน้านี้ใน C++11 และ C++14 static_assert มีฟังก์ชันการทำงานที่แตกต่างกัน ซึ่งหมายความว่าเราต้องเขียนข้อความของเราเองในขณะที่กำหนด static_assert อย่างไรก็ตาม ใน C++ 17 static_assert สามารถเรียกใช้งานได้โดยไม่ต้องส่งข้อความ

มันเข้ากันได้กับฟังก์ชั่นไลบรารียืนยันอื่น ๆ เช่น BOOST_STATIC_ASSERT เช่นกัน

ไวยากรณ์

{
   auto __range= For-range-Intializer;
   auto __begin= begin-expression;
   auto __end= end-expression;
   for(; __begin!= __end; ++__begin){
      range-declaration= *__begin;
      statement
   }
}

ประเภทของ __begin และ __end จะแตกต่างกัน ต้องใช้ตัวดำเนินการเปรียบเทียบเท่านั้น การเปลี่ยนแปลงนั้นไม่มีผลกับลูปที่มีอยู่ แต่มีตัวเลือกเพิ่มเติมสำหรับไลบรารี ตัวอย่างเช่น การเปลี่ยนแปลงเล็กน้อยนี้ทำให้ช่วง TS (และช่วงใน C++20) ทำงานกับลูปแบบอิงตามช่วงได้

ใน C++11 ตามช่วง สำหรับ ลูป -

for (for-range-declaration : for-range-initializer){
   statement;
}

ในมาตรฐาน C++14 นิพจน์ลูปดังกล่าวเทียบเท่ากับโค้ดต่อไปนี้ −

{
   auto __range = for-initializer;
   for ( auto __begin= begin-expresson, __end = end-expression; __begin != __end; ++__begin ){
      for-range-declaration = *__begin;
         statement
   }
}

ตัวอย่าง

#include <bits/stdc++.h>
using namespace std;
template <typename T, size_t n, typename F> //Template Declaration
void fillarray (array<T, N> & a, F && f) //Function to store the values{
   static_assert(is_convertible<typename result_of<F()>::type, T>::value,"Incompatible type returned by fun()"); //static_assert signature to ommit the errors.
   for (auto x : a)
      x = f();
}
int main (){
   array<vector<string>, 20> a;
   fillarray(a, []() { return vector<string>{"TutorialsPoint"}; });
   return 0;
}

ผลลัพธ์

…
…
…
prog.cpp:20:61: required from here
prog.cpp:10:5: error: static assertion failed:
Incompatible type returned by fun()