GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — C++ の面白いコード、トリッキーなコードの話 · Issue #9 · cppmap/cppmap.docs

C++ の面白いコード、トリッキーなコードの話 #9

New issue
Copy link
New issue
Copy link
Open
Open
C++ の面白いコード、トリッキーなコードの話#9
Copy link
Labels
募集

Description

@Reputeless
Reputeless
opened on Mar 12, 2019
Issue body actions

実用性はなくてもいいので、面白いネタ的なコードや不思議な文法、仕様のハックなどがあれば教えてください。ある程度たまったら記事にします。

  • 数行~十数行で完結するぐらいが好ましいです
  • マイナーなものでも有名なものでも OK です

(例) コメントアウトのトリック

Activity

  1. Reputeless
    added
    募集
    on Mar 12, 2019
  2. faithandbrave commented on Mar 12, 2019

    @faithandbrave
    faithandbrave
    on Mar 12, 2019
    Contributor
    More actions

    よくある、ヘッダファイル以外をインクルードするとかは、データをコンパイル時に埋め込める便利な記法です。

    int ar[] = {
        #include "a.csv"
    };

    ヘッダファイル内で.cpp (相当のファイル) をインクルードするオプションを用意して、ヘッダオンリー化できるようにしているのとかは、ライブラリを作るにあたって設計選択のひとつになっています。

    https://github.com/boostorg/chrono/blob/develop/include/boost/chrono/thread_clock.hpp

    (最近はシングルヘッダ版を自動生成するとかもありますが)

    Reacted by Ryo Suzuki
  3. faithandbrave commented on Mar 12, 2019

    @faithandbrave
    faithandbrave
    on Mar 12, 2019
    Contributor
    More actions

    プリプロセス関係だと、文字列リテラルの結合とかも、マイナーですがたまに便利ですね。自前のprintfやassertを作るときにも使いますし、長い文字列リテラルを分割して書くのにも便利です。

    #include <cstdio>
    
    #define INFO(fmt, ...) std::printf("[info] " fmt "\n" __VA_OPT__(,) __VA_ARGS__)
    #define DEBUG(fmt, ...) std::printf("[debug] " fmt "\n" __VA_OPT__(,) __VA_ARGS__)
    
    int main()
    {
        INFO("hello");
        DEBUG("hello %d", 123);
    }
    #include <iostream>
    
    int main()
    {
        std::string help = "The application is designed by ME.\n"
                           "Welcome my application";
    
        std::cout << help << std::endl;
    }
    Reacted by Ryo Suzuki and onihusube
  4. faithandbrave commented on Mar 12, 2019

    @faithandbrave
    faithandbrave
    on Mar 12, 2019
    Contributor
    More actions

    csvのインクルードとかを多用するようになると、以前私がブログに書いた以下のようなものがほしくなります。

    • インクルードするディレクトリをマクロ定数として持つ
  5. Reputeless commented on Mar 12, 2019

    @Reputeless
    Reputeless
    on Mar 12, 2019
    MemberAuthor
    More actions

    コメントありがとうございます! 引き続き募集してます。

    --> 演算子

    #include <iostream>
    
    int main()
    {
    	int i = 10;
    
    	while (i --> 0)
    	{
    		std::cout << i << '\n';
    	}
    }
  6. wx257osn2 commented on Mar 12, 2019

    @wx257osn2
    wx257osn2
    on Mar 12, 2019
    Contributor
    More actions

    template関数のオーバーロードに優先順位を付けるやつ:

    #include<cstdint>
    template<std::size_t N>struct priority : priority<N-1>{};
    template<>             struct priority<0>{};
    
    #include<iostream>
    #include<type_traits>
    template<
      typename T,
      std::enable_if_t<std::is_same<std::decay_t<T>, float>::value, std::nullptr_t> = nullptr
    >
    void f_impl(T t, priority<1>){std::cout << "float " << t << std::endl;}
    template<typename T>
    void f_impl(T t, priority<0>){std::cout << "T " << t << std::endl;}
    
    template<typename T>
    void f(T&& t){f_impl(std::forward<T>(t), priority<1>{});}
    
    int main(){
      f(3.1);
      f(3.14f);
      f("3.141592");
    }

    Wandbox

    Reacted by Ryo Suzuki
  7. onihusube commented on Mar 12, 2019

    @onihusube
    onihusube
    on Mar 12, 2019
    Contributor
    More actions

    面白いかは分からないですが、リテラル0だけを受け取る関数(nullptrからは目を逸らして・・・)

    struct minus {
      constexpr bool operator<(std::nullptr_t) {
        return true;
      }
      
      constexpr bool operator>(std::nullptr_t) {
        return false;
      }
    };
    
    void f(std::nullptr_t) {
      std::cout << "literal 0" << std::endl;
    }

    https://wandbox.org/permlink/sDe2GzeQuPk1hMT0

    Reacted by Ryo Suzuki and yumetodo
  8. Fuyutsubaki commented on Mar 12, 2019

    @Fuyutsubaki
    Fuyutsubaki
    on Mar 12, 2019
    Contributor
    More actions

    コンパイルできそうだけどできないコードたち

    void f2(std::shared_ptr<int>=0);
    void f(int*=0);
    int a[3];
    a[[]{return 0;}()];
    

    https://wandbox.org/permlink/P76EMNyoE6FAQaDs

    Reacted by Ryo Suzuki
    Reacted by yoh
  9. yumetodo commented on Mar 13, 2019

    @yumetodo
    yumetodo
    on Mar 13, 2019
    Contributor
    More actions

    false_vを作らないでlambda式でif constexpr内のstatic_assertの評価を遅延させるやつ

    #include <type_traits>
    
    template <typename T>
    void f(T)
    {
      if constexpr (std::is_same_v<T, int>)
      {
        // Tがintのときのみ評価される
        static_assert([]{return false;}());
      }
    }
    
    int main()
    {
      f(2.4);
      f(3);
    }

    https://cpprefjp.github.io/lang/cpp17/if_constexpr.html
    cpprefjp/site#577
    by @alphya

    Reacted by onihusube
  10. yumetodo commented on Mar 13, 2019

    @yumetodo
    yumetodo
    on Mar 13, 2019
    Contributor
    More actions

    input streamの中身をまるごとoutput streamにぶちこむやつ

    os << is.rdbuf();
  11. rhysd commented on Mar 14, 2019

    @rhysd
    rhysd
    on Mar 14, 2019
    Contributor
    More actions

    Most vexing parse: https://en.wikipedia.org/wiki/Most_vexing_parse

    Reacted by Ryo Suzuki
  12. agehama commented on Mar 14, 2019

    @agehama
    agehama
    on Mar 14, 2019
    More actions

    暗黙の型変換にやられるやつ(ただのバグ)

    #include <iostream>
    
    int main()
    {
        if(-1 < 1u)
        {
            std::cout << "-1 < 1u";
        }
        else
        {
            std::cout << "-1 > 1u";
        }
    }
    
    Reacted by Ryo Suzuki
  13. agehama commented on Mar 14, 2019

    @agehama
    agehama
    on Mar 14, 2019
    More actions

    名前空間の付け忘れにやられるやつ(ただのバグ)

    #include <iostream>
    #include <cmath>
    
    int main()
    {
        //std::cout << std::abs(0.5); // 0.5
        std::cout << abs(0.5);        // 0
    }
    
  14. nekko1119 commented on Mar 16, 2019

    @nekko1119
    nekko1119
    on Mar 16, 2019
    Contributor
    More actions
    template <int>
    int a = 0;
    
    int main() {
        //a<10>= 1; // 動かない
        a<10> = 1;
    }

    スペースの有無で演算子と解釈されるかどうか異なります

    Reacted by Ryo Suzuki and yumetodo
  15. Fuyutsubaki commented on Mar 18, 2019

    @Fuyutsubaki
    Fuyutsubaki
    on Mar 18, 2019
    Contributor
    More actions

    (特別C++に限らないけけど) Fast inverse square root とか

    Reacted by Ryo Suzuki
  16. zxc-key commented on Oct 27, 2020

    @zxc-key
    zxc-key
    on Oct 27, 2020
    More actions

    https://wandbox.org/permlink/fXQKYqQAgMiyMMf9

    • enumをコンパイル時定数として使う
    • enumの最後の要素を要素数として使う
    • 配列の変数名とインデックスを逆にしても動作する
  17. yumetodo commented on Oct 27, 2020

    @yumetodo
    yumetodo
    on Oct 27, 2020
    Contributor
    More actions

    constexprが普通に使えるこんにちは出番がなさそう・・・?

  18. Reputeless commented on Oct 27, 2020

    @Reputeless
    Reputeless
    on Oct 27, 2020
    MemberAuthor
    More actions

    @zxc-key 提案ありがとうございます。

    1. enum をコンパイル時定数として扱うのは今では古いテクニック (現在は constexpr) で、ある程度知られているとも思います
    2. 「最後尾 = 要素数」は、サンプルコードでいうと _0 = 100 のようなコードで不正になります。magic_enum というライブラリの enum_count では、複雑なテクニックでその問題も回避しています
    3. cppmap 掲載済みです https://cppmap.github.io/articles/it-compiles/#_2

    【面白いネタ的なコードや不思議な文法】として cppmap で新規に取り上げるネタはありませんでしたが、また面白いコードを見つけたら教えてください 🖐

    Reacted by zxc
  19. yohhoy commented on Mar 5, 2021

    @yohhoy
    yohhoy
    on Mar 5, 2021
    Contributor
    More actions
    int main()
    {
      []{};
      []{}();
      [](){};
      [](){}();
      [[]][]{};
      []()[[]]{};
      [[]][]{}();
      [[]][](){};
      []()[[]]{}();
      [[]][](){}();
      [[]][]()[[]]{};
      [[]][]()[[]]{}();
    }

    ネタの一つとして提供:https://twitter.com/yohhoy/status/1367790416007897089

    Reacted by Ryo Suzuki
  20. yaito3014 commented on Mar 7, 2021

    @yaito3014
    yaito3014
    on Mar 7, 2021
    More actions
    #include <iostream>
    
    using T = int&;
    void f(T&) { std::cout << "non-const" << std::endl; }
    void f(const T&) { std::cout << "const" << std::endl; }
    
    int main() {
      int x;
      f(x);
    }
    

    コンパイルできそうでできないやつです。

    Reacted by Ryo Suzuki
  21. yumetodo commented on Mar 7, 2021

    @yumetodo
    yumetodo
    on Mar 7, 2021
    Contributor
    More actions
    #include <type_traits>
    using T = int&;
    using T2 = const T&;
    static_assert(std::is_same_v<T, T2>);

    なるほど・・・?
    https://wandbox.org/permlink/SVngPcUtKYXAL72O

  22. Ryoga-exe commented on Mar 8, 2021

    @Ryoga-exe
    Ryoga-exe
    on Mar 8, 2021
    More actions

    長い演算子 (演算子の優先順位的にできるやつ)

    #include <iostream>
    
    int main() {
      int a = 10, b = 10;
      a = a +-+-+-+-+-+-+-+-+ 6 +-+-+-+-+-+-+-+-+ 5;
      b = b + + + + + + + + + 6 - - - - - - - - - 5;
      std::cout << a << '\n';
      std::cout << b << '\n';
      return 0;
    }
    Reacted by Ryo Suzuki
  23. faithandbrave commented on Mar 11, 2025

    @faithandbrave
    faithandbrave
    on Mar 11, 2025
    Contributor
    More actions

    assert(!"message");は有名ですね。

    #include <cassert>
    #include <iostream>
    
    void f(int x) {
      if (x >= 0) {
        std::cout << x << std::endl;
      }
      else {
        assert(!"f() argument be positive");
      }
    }
    
    int main() {
      f(-1);
    }

    出力:

    prog.exe: prog.cc:9: void f(int): Assertion `!"f() argument be positive"' failed.
    
    Reacted by Ryo Suzuki
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    募集

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions

      You are visitor 01402503 — GeezerVison does not store the pages you look up.
      Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.