Skip to Content
C++の紹介 (Japanese Edition)
book

C++の紹介 (Japanese Edition)

by Frances Buontempo
March 2026
Intermediate
348 pages
4h 30m
Japanese
O'Reilly Media, Inc.
Content preview from C++の紹介 (Japanese Edition)

第14章 std::variant と std::visitの使用

この作品はAIを使って翻訳されている。ご意見、ご感想をお待ちしている:translation-feedback@oreilly.com

抽象基底クラスから始めてインタフェースを提供し、振る舞いを変える方法を見てきた。 必要に応じて派生クラスを追加し、様々な実装を提供できる。 C++でこれを実現する構成要素を教えるのに数章を費やした。 必要な要素はいくつかあるが、この手法は拡張性がある。既存のコードを変更せずに、必要に応じて派生型を追加し続けられるのだ。

C++の別の機能であるstd::variantも、振る舞いを変えるために使える。 std::variantはC++17で導入されたクラステンプレートだ。 std::variantは複数の代替型のうちの1つを保持する。Cプログラマなら、これはでunionに似た類似性がある手法だと気づくだろう。 型同士は全く無関係でも構わない。 この手法では事前に型セットを固定する必要があるため、OOPほど拡張性に優れていない。 しかしstd::variantは型セットの振る舞いを非侵襲的に拡張できる。 クラスに機能を追加する場合、基底クラスに新メソッドを追加すれば派生クラス全てに影響する。 std ::variantを使えば、内部の型を変更せずに新関数を提供できる。 OOPは新型の追加は容易だが、新操作の追加は困難だ。 変種型は新操作の追加は容易だが、新型の追加は困難である。つまりOOPと変種型にはトレードオフがある。

この章では、取引ゲームにボーナス支払いやペナルティ(例えば利息支払い)を追加するためにstd::variantを使う方法を示す。 また、異なる設計目標を持つが同様に可変型を保持するstd::optionalstd::any の二つの機能についても触れる。

std::variantの作成と使用

取引ゲームに追加要素を加えよう。 ニュース見出し(はstd::string型)に加え、罰金・贈与・利息支払いなどを表す他の型を作成できる。 ランダムにいずれかを返す新関数を作成する。 イベント発生時は、std::stringを表示するかメッセージを表示し、資金を調整して報告する。

無関係な複数の型から一つを返すにはどうするか? 基底クラスがあれば、そのクラスのスマートポインタを返せばよい。ポリモーフィズムが振る舞いを請け負う。 無関係な型の場合、それは不可能だ。 しかし、std::variantに任意の型を格納することはできる。

まず、罰金・贈与・利息支払い用の新型をevents.hファイルに定義しよう。 イベントは偶発的に発生させるため、非イベントも定義できる。 これらをstd::variantで扱う:

#include <iostream>
#include <string>
#include <variant>

namespace stock_prices
{
    struct Nothing 1
    {
    };

    struct FixedFine 
    {
        double fine{};
    };

    struct Gift 
    {
        double gift{};
    };

    struct InterestPayment 
    {
        double ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

エージェントメッシュ (Japanese Edition)

エージェントメッシュ (Japanese Edition)

Eric Broda, Davis Broda

Publisher Resources

ISBN: 0642572352653