LoginSignup
0
1

More than 5 years have passed since last update.

optional を C++で試す

Posted at

swiftのオプショナル型非常に便利なんだけど
C++でもできるっぽい。

#include <experimental/optional>
#include <iostream>
#include <string>
using namespace std;
using namespace std::experimental;

int main()
{

    optional<string> dummy1 = string("hello");
    optional<string> dummy2; // empty nullptr

    if(dummy1){ // string
        cout << *dummy1 << endl;
    }

    if(dummy2){ // empty
        cout << *dummy2 << endl;
    }

    dummy2 = dummy1; // copy

    if(dummy2){ // ask length
        cout << *dummy2 << endl;
    }


    return 0;
}

まぁswift !にあたるのが * だね。
普通にifでヌル除外とかができる。
値を取り出すには*でswiftのように明示的にunwrapしなきゃいけないので、まぁヌルチェックは忘れなくはなりそう。

ただ、ネックはexperimentalのフォルダに入っててしかもC++11じゃこのコードコンパイルできないのね。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1