C++」カテゴリーアーカイブ

江添本写経scope_exit

写経中にstd::scope_exitというものが出てきたが、(本が書かれている時点ではC++20に公式に取り込まれる予定だったみたいだが)C++20ではまだ取り込まれていない模様。

experimental/scopeというとこで実験的に入っているっぽい。

#include <experimental/scope>してstd::experimental::scope_exitすると使える模様。

experimentalなので何かあるかもしれないが写経はこれで使ってみる。

#include <iostream>
#include <experimental/scope>

void example() {
    auto cleanup = std::experimental::scope_exit([] {
        std::cout << "Scope exited.\n";
    });

    std::cout << "Doing work inside the scope.\n";
}

int main() {
    example();
    return 0;
}

な感じ。

C++勉強メモ

やりそうなエラー

stringリテラルの設定もれ

string型のリテラルはincludeとnamespace設定がいる

忘れた場合のエラーメッセージは

vscode

ユーザー定義のリテラル演算子が見つかりませんC/C++(2486)

gcc

chap3.cpp:4:18: error: unable to find string literal operator ‘operator""s’ with ‘const char [6]’, ‘long unsigned int’ arguments
4 | std::cout << "hoge\n"s;
| ^~~~~~~~~
make: *** [Makefile:6: chap3.o] Error 1

補足

C++11でリテラル演算子をユーザー定義できるようになったとのこと。自分で定義するなら

ただし、自作する場合はアンスコ(_)で始めろと。

試しに自作したら

上でも動いた