C++14/17 機能

最新C++の便利な機能.

std::make_unique (C++14)

#include <iostream>
#include <memory>

class Resource {
public:
    void use() { std::cout << "使用中" << std::endl; }
    ~Resource() { std::cout << "破棄" << std::endl; }
};

int main() {
    {
        auto res = std::make_unique<Resource>();
        res->use();
    }  // 自動破棄
    
    return 0;
}

使用中
破棄

構造化バインディング (C++17)

#include <iostream>
#include <map>
#include <string>

int main() {
    std::map<std::string, int> data = {
        {"a", 1}, {"b", 2}, {"c", 3}
    };
    
    // 構造化バインディング
    for (const auto& [key, value] : data) {
        std::cout << key << ": " << value << std::endl;
    }
    
    return 0;
}

a: 1
b: 2
c: 3

コンセプト (C++20)

#include <iostream>
#include <concepts>

// テンプレート制約
template<std::integral T>
T add(T a, T b) {
    return a + b;
}

int main() {
    std::cout << add(3, 5) << std::endl;
    // std::cout << add(3.5, 2.5) << std::endl;  // エラー!
    
    return 0;
}

8

std::optional (C++17)

#include <iostream>
#include <optional>
#include <string>

std::optional<int> toInt(const std::string& s) {
    try {
        return std::stoi(s);
    } catch (...) {
        return std::nullopt;
    }
}

int main() {
    if (auto val = toInt("42")) {
        std::cout << "値: " << *val << std::endl;
    }
    
    if (auto val = toInt("invalid")) {
        std::cout << "値: " << *val << std::endl;
    } else {
        std::cout << "変換失敗" << std::endl;
    }
    
    return 0;
}

値: 42
変換失敗

ポイント

  • make_unique で安全に unique_ptr 生成
  • 構造化バインディングでマップを簡潔に
  • std::optional で null 安全性