LoginSignup
78
78

More than 5 years have passed since last update.

C++コード逆引き

Last updated at Posted at 2014-07-19

概要

初めてラムダ式を見た時、うわなにこれってなりませんでしたか?
調べようにもコードで検索しても記号が多いと検索性が低いです。
そこで、コードから検索できるようなリストが欲しくなったので作成しました。

また、知らなければ調べる事ができないので特定のキーワードも記述しました。

最低限のコードしか書いていないので、名前の分かった構文やキーワードはどんどん検索しましょう。

alignas, alignof

C++11

alignas(16) char a;      // アライメント指定
struct alignas(32) B;    // 構造体のアライメント指定
std::cout << alignof(a); // アライメント取得

auto

C

auto int x; // 記憶クラス指定子, C++では11から使えない

C++11

// 初期化子からの型導出
std::vector<int> v;
auto i = v.begin();

// 戻り値の型の後置
auto f() -> int { return 1; }

C++14

// 通常関数の戻り値型推論
auto f() { return 1; }

returnとreturn (…)の違い
http://faithandbrave.hateblo.jp/entry/2014/06/11/164158

// 戻り値型推論の参照返し
decltype(auto) foo() {
    static int a;
    return ( a );
}
// ジェネリックラムダ

// 引数にautoが使える
auto Sum = [](auto a, decltype(a) b) { return a + b; };

// テンプレートも使える
auto NumElements = []<int N>(auto (&a)[N]) { return N; };

// {}を省略できる
auto L = [&](auto a) a;

// 関数ポインタに直接代入できる
int (*fp)(int, int) = [](auto a, decltype(a) b) { return a + b; };

// 可変引数も使える
auto print = []( auto... args )     // パラメータパック
{
    auto f = []( int x ) -> int { return x; };
    std::cout << f( args... );      // 展開
};
print( 1 );

C++17

// structured bindings
auto [iterator, success] = m.insert({"Hello", 42});
// Declaring non-type template parameters with auto
template <auto v>    class Y { };

cast

C++03

// Cスタイルキャスト a = (int)(0.0); よりもこっち推奨
auto a = static_cast< int >( 0.0 );
auto b = const_cast< const int* >( &a );
auto c = reinterpret_cast< long int >( b );

// ダウンキャスト、非推奨
Foo* f = dynamic_cast< Foo* >( base );

constexpr

C++11

// コンパイル時に関数が使える
constexpr bool TrueFunction() { return true; }

C++14

// constexpr関数の制限緩和
constexpr int Abs( int a ) {
    // if文や変数への代入ができる
    if( a < 0 ) a = -a;
    return a;
}
// 軽量コンセプト( Concept Lite )のルール定義
template <class T>
constexpr bool LessThanComparable() {
    return has_less<T>::value;
}

decltype

C++11

// 引数の型を返す
auto Foo( int a ) -> decltype(a) { return a; }

C++14

戻り値型推論の参照返し
→ autoの項目参照

default, delete

C++11

// コンパイラが自動的に生成する関数の制御( Defaulted and Deleted Functions )
struct noncopyable {
    // コピーできない
    noncopyable() = default;
    noncopyable(const noncopyable&) = delete;
    noncopyable& operator=(const noncopyable&) = delete;
};

enum

C++11

// enumの先行宣言( Forward declaration of enumerations )
enum Enumerations : int;
// Strongly Typed Enums, scoped enum
enum class Color { Red };
Color c = Color::Red;

explicit

C++03

struct Foo {
    // 暗黙のコンストラクタ変換の防止
    explicit Foo(int a){}
};

C++11

struct Foo
{
    // 暗黙のキャスト防止( explicit conversion )
    explicit operator int() const;
};

extern

C++11

// Extern Template
// この翻訳単位ではテンプレートのインスタンス化をしない
extern template class std::vector<Foo>;

for

C++11

// Range-base for文
// コンテナや配列をシンプルにループできる
for (int i : {1, 2, 3}){}

friend

C++11

// 拡張フレンド宣言( Extended friend Declarations )
template <class T>
class Foo {
    friend T; // テンプレートパラメータをfriendに
};

inline

C++11

// 透過的な名前空間( inline namespace )
inline namespace tr1{}

mutable

C++03

struct Foo {
    // const修飾されたメソッド内でも変更できる
    mutable int a;
};

nullptr

C++11

// ヌルポインタを表すキーワード、0やNULLよりこっち推奨
int *a = nullptr;

operator

C++11

// ユーザー定義リテラル
std::string operator "" _addfoo ( const char* p, std::size_t n ) {
    return std::string(p, n) + "foo";
}

unsigned long long int operator "" _twice ( unsigned long long int value )
{
    return value * 2 ;
}

int main()
{
    std::cout << 1234_twice << std::endl ;
    std::cout << "test"_addfoo << std::endl ;
}

override

C++11

struct Foo : public Base {
    // オーバーライドしていなかった場合エラーになる
    void Bar() override {}
};

R"( )"

C++11

// 生文字列リテラル( raw string literal )
const char* a = R"(\)";

// ワイド文字列
const wchar_t *a = LR"(\)";

// utf-16, utf-32 文字列
const char16_t *b = uR"(\)";
const char32_t *c = UR"(\)";

// utf-8エンコード文字列
const char *d = u8R"(\)";

sizeof

C++11

template <class... args>
struct Count {
    // パラメータ数を取得できる
    static const int value = sizeof...(args);
};
// 拡張sizeof
struct hoge {
    int id;
};
// staticでないメンバ変数を、インスタンス作成なしにsizeofできる
sizeof(hoge::id);

static_assert

C++11

// 条件を指定してエラーにできる
static_assert( false, "error" );

template

C++03

// 関数テンプレート
template< class T >
void Foo( T t ){}
// クラステンプレート
template< class T >
struct Foo {
    T t;
};
// クラスメンバテンプレート
struct Foo {
    template< class T >
    void Bar( T t ) {}
};
template< class T >
void Foo( T t ){}

// 明示的特殊化
template<>
void Foo( int t ){}

C++11

// エイリアステンプレート( Template Aliases )
template <class T>
using Vec = vector<T>;

C++14

// 変数テンプレート
template <int N>
int foo = N;
// 軽量コンセプト( Concept Lite )
// 制約テンプレート
template <Foo T> // Foo は constexpr述語関数
T Bar( T a ){}

thread_local

C++11

// スレッドごとに一度だけインスタンス化される
thread_local int a = 0;

typeid

C++03

// 型の情報を取得する
int a;
if( typeid(a) ==typeid(int) ){}

typename

C++03

template< class T >
void Foo( T t ) {
    // T::Barが型であることを明示する
    typename T::Bar* p;
}

union

C++03

// 共用体、同じメモリ領域を複数の型が共有する
union Foo {
    int a;
};

C++11

// 無制限Union( Unrestricted Unions )
union Foo {
    std::vector<int> v;
    static int b;
    void Bar(){}
};

using

C++11

// 継承コンストラクタ(Inheriting Constructors)
struct base { base(int){} };
struct derived : base {
    // derived::derived(int) が使えるようになる
    using base::base;
};

エイリアステンプレート( Template Aliases )
→ templateの項目参照

volatile

C++03

// コンパイラ最適化を抑制する
volatile int a;

0b

C++14

// 2進数リテラル
int a = 0b1100;
int b = 0B1100; // 同じ

...

C++11

// Variadic Template Template Parameters
template<template<typename...> class T, typename... U>
struct eval<T<U...> > { /*...*/ };
// 可変長テンプレート引数( Variadic Templates )
template <class... Types>
struct Foo {
    // 引数の個数を取得
    static const int value = sizeof...(Types);
};
// 可変長引数マクロ
#define ROTATE(...) ROTATE_I(__VA_ARGS__)
#define ROTATE_I(x, ...) __VA_ARGS__, x

C++14

ジェネリックラムダの可変パラメータに
→ autoの項目参照

C++17

// Fold expressions
template<typename ... Args>
auto sum(Args && ... args)
{
    // foldには括弧も必要
    return (args + ... );
}

( )

C++11

// メンバ初期化子(Class member initializers)
// =の項目も参照
class Foo {
    int a;
public:
    // コンストラクタの前に初期化を行える
    Foo() : a( 0 ) {}
};
// デリゲーティング・コンストラクタ(delegating constructor)
class Foo {
public:
    Foo() {}
    // コンストラクタから別のコンストラクタを呼べる
    Foo(int a) : Foo() {}
};

C++14

戻り値型推論の参照返しでのreturn (...);
→ autoの項目参照

< >

C++03

→ templateの項目参照

{ }

C++11

// Uniform initialization

// ただのサンプルクラス
class Foo {
public:
    Foo( int x, int y ){}
};

// Foo f( 0, 0 );と同じ
// ただしコンストラクタにstd::initializer_listが設定されていた場合そちらが優先される
// most vexing parse の様な問題を回避できる
Foo f1{ 0, 0 };
Foo f2({0, 0});
Foo f3 = {0, 0};
Foo f4 = Foo{0, 0};

[ ]

C++11

// [] の名称:ラムダ導入子(lambda-introducer)
// ラムダ式色々
[]{};
[=](){};
[&]() -> void {};

// 変数のキャプチャ
int a = 0;
[a](int a) -> void {};
[&,a]{ return true; };

C++14

// 実行時サイズの配列
void Foo( int n ) {
    // nは定数じゃない
    int a[ n ];
}
// 一般化されたラムダキャプチャ
[x = a, &y = a]{}; // 式が使える
[Foo()]{};         // 関数が使える

ジェネリックラムダ
→ autoの項目参照

C++17

structured bindings
→ autoの項目参照

[[ ]]

一般化された属性(attribute)

C++11

// 関数が返らない指定
[[ noreturn ]] int Foo (){ throw "error"; } // どっちでも良さそう
int Foo [[ noreturn ]] (){ throw "error"; }

C++14 or C++1y

// 使うとwarningを出してくれる
[[deprecated]] void Foo (){}

&, &&

C++11

// 右辺値参照(Rvalue reference)
int&& a = 1;
// ムーブ・セマンティクス(Move semantics)
struct Foo {
    Foo(Foo&&);
    Foo& operator=(Foo&&);
};
// メンバ関数のlvalue/rvalue修飾
struct Foo {
    void Bar() const & {}
    void Bar() &&      {}
};

=

C++11

// メンバ初期化子(Class member initializers)
class Foo {
    int a = 0; // 初期値を設定できる
};
// Default template arguments for function templates
template <class T = int > // デフォルト引数が設定できる
void Foo(T t = 0 ){}

:

C++03

// ビットフィールド
struct Foo { int a : 1; };

C++11

// 範囲for文(ranged-base for loop)
std::array<int, 3> a;
for(int b : a) {}

C++17

// Nested namespace definition
namespace A::B::C {}

;

C++17

auto pair = std::make_pair(false, 0);
// Selection statements with initializer
if(auto a = tuple; a.first){
    std::cout << a.second;
}

'

C++14

// 数値リテラルの桁区切り文字
int a = 1'234'567;

" "

C++03

// ワイド文字列
const wchar_t *a = L"a";

C++11

// utf-16, utf-32 文字列
const char16_t *b = u"a";
const char32_t *c = U"a";

// utf-8エンコード文字列
const char *d = u8"a";
// ユニバーサルキャラクタ名( Universal Character Names in Literals )
char16_t *s = u"\U00020BB7野家"; // 吉野家

生文字リテラル
→ R"( )" の項目参照

ユーザー定義リテラル
→ operatorの項目参照

動作環境

wandbox
http://melpon.org/wandbox

clang 3.4 (tags/RELEASE_34/final)

C++17
clang 3.9

参考

まとめ

https://sites.google.com/site/cpprefjp/implementation-status
http://docwiki.embarcadero.com/RADStudio/XE3/ja/C%2B%2B11_%E3%81%AE%E6%A9%9F%E8%83%BD%EF%BC%88BCC64%EF%BC%89
http://www32.ocn.ne.jp/~ons/text/CPP0xFAQ.html.ja

ブログ

http://cpplover.blogspot.jp/
http://faithandbrave.hateblo.jp/

スライド

C++17

https://cpplover.blogspot.jp/2015/03/c17.html
http://stackoverflow.com/documentation/c%2b%2b/487/returning-several-values-from-a-function#t=201611241000193118802
http://stackoverflow.com/questions/38060436/what-are-the-new-features-in-c17

78
78
2

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
78
78