반응형

C++ 코드를 보다보니 [[ ~ ]] 와 같은 형식으로 작성된 부분 있었다.

 

뭔가 싶어서 검색해보니 컴파일러에게 코드에 대해서 좀 더 명확하게 힌트를 제공하는 기능이라고 한다.

 

그중에서 자주 사용할것 같은 attribute만 간단하게 정리해보고자 한다. (개인적인 기준;;)

 

1. [[nodiscard]] - C++17

 

이 attribute가 붙은 함수나 attibute가 붙은 enum, class등을 리턴하는 함수를 만들었다면

해당 함수를 호출할때는 리턴값을 받아야 한다고 컴파일러에 알려주는 것이다.

이는 컴파일 시점에 워닝으로 알려준다.

 

[[nodiscard]] int strategic_value(int x, int y) { return x^y; }

int main()
{
  strategic_value(); // warning
  auto v = strategic_value(); // ok

  return 0;
}

 

[[nodiscard("string"]] - C++ 20은 워닝 메시지에 "string" 부분도 같이 남겨준다.

 

2. [[deprecated]] / [[deprecated("string") - C++14

 

해당 attribute가 붙은 함수를 사용하면 사용은 가능하지만 앞으로 제거될 수 있음을 워닝으로 알려준다.

엔진이나 라이브러리를 만들때 많이 사용될 것 같다.

언리얼 엔진에서도 버전업 하고 빌드해보면 나올때가 있다. 그러면 최신에 맞게 코드를 수정해주곤 한다.

 

[[deprecated]]
void TriassicPeriod() {
    std::clog << "Triassic Period: [251.9 - 208.5] million years ago.\n";
}
 
int main()
{
    TriassicPeriod(); // warning
    return 0;
}

 

3. [[fallthrough]] - C++17

 

switch / case 문을 사용하다보면 fallthrough 기능을 사용하곤한다.

컴파일러에 따라서 해당 부분을 워닝처리할때가 있는데 컴파일러에 명확하게

내가 fallthrough를 한거니까 워닝처리를 하지 말라고 하는 것이다.

 

void f(int n) {
  void g(), h(), i();
  switch (n) {
    case 1:
    case 2:
      g();
     [[fallthrough]];
    case 3: // no warning on fallthrough
    ..
  }
}

몇가지 더 있기도 하고 추가될 예정인것 같지만 일단 이정도만 알고 사용해도 되지 않을까 싶다.

반응형
Posted by msparkms
,
반응형

std::string을 사용하면서 printf처럼 formatting 기능을 사용하고 싶었다.

혹시 새로운 기능이 없을까 하고 검색해보니 c++20에 std::format이라는 기능이 추가되었다고 한다.

std::format은 아래와 같이 std::string_view를 인자로 받는다.

template<class... Args>
string format(string_view fmt, const Args&... args);

string_view이기 때문에 그냥 const char*를 넘겨도 된다.

 

기본 사용방법은 아래와 같다.

std::format("{} {}!", "Hello", "world");	// Hello world!

{} 위치에 배치된다고 보면 된다.

 

{} 이곳에 들어갈 여러가지 기능들은 너무 많아서 링크로 대신한다.

필요할때 마다 검색해서 사용해봐야 될 것 같다.

https://en.cppreference.com/w/cpp/utility/format/formatter#Standard_format_specification

 

std::formatter - cppreference.com

template struct formatter; (since C++20) The enabled specializations of formatter define formatting rules for a given type. Enabled specializations meet the Formatter requirements. In particular, they define callables parse and format. For all types T and

en.cppreference.com

 

format을 사용하기 위해서는 Visual Studio 2019를 16.10 버전 이상으로 올려야 하고

C++ 버전은 latest로 변경해야 한다.

 

Vector3를 String으로 변경하는 간단한 코드를 예제로 남기고 마무리하면 될 것 같다.

class Vector3
{
public:
  float x_, y_, z_;
  
public:
  std::string toString()
  {
    return std::format("( {:.2f}, {:.2f}, {:.2f} )", x_, y_, z_);
  }
};
반응형
Posted by msparkms
,