0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ユーザー定義リテラルの例

Last updated at Posted at 2013-04-29

某所で話題になったユーザー定義リテラル。
私自信、存在を知っているだけで書いたことはなかったので、書いてみた。

とはいえ
http://cpplover.blogspot.jp/2012/02/blog-post_16.html
にたぶん全部書いてあるので、このコードを見るよりも上記のリンク先を見るのがよいかもしれない。

// compiled with followings:
//    clang -c -std=c++11 udl.cpp
//    g++ udl.o

# include <iostream>

struct gram{
    double m;
    gram( double v ) : m(v){}
};

gram 
operator+( gram const & a, gram const & b )
{
    return gram( a.m + b.m );
}

std::ostream &
operator<<( std::ostream & o, gram const & g )
{
    return o << g.m << "g";
}

typedef unsigned long long ull_t;

gram operator "" _g( long double v ){  return gram( v );  }
gram operator "" _g( ull_t v ){  return gram( v );  }
gram operator "" _kg( ull_t v ){  return gram( v*1e3 );  }
gram operator "" _kg( long double v ){  return gram( v*1e3 );  }

int main()
{
    std::cout 
        << 1234_g << "\n"       // => 1234g
        << 10_g +0.2_kg<< "\n"       // => 210g
        << 1e2_g +1_kg<< "\n";       // => 1100g
    return 0;
}

仕事以外では是非乱用したい。

ちなみに gram operator "" _μg( ull_t v ){/*略*/} はコンパイルエラーだった。残念。

あと。
clang だけだとリンクが通らない。なんでだろ。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?