2015年5月19日火曜日

limits (C++)

プリミティブ型の最大値や最小値を取得する際、マクロ変数から取得することも可能だが、型安全な定数やメタ関数を利用して取得する。

 メタ関数は、こんな形式の関数

meta-function<type ...>::value()
typeに対してプリミティブ型でなく、typedefした型を入力すれば、型の変更に合わせてコードを書き換える必要なく値を取得できる。

//
// limits.cpp
// CplusplusPractice
//
// Created by masai on 2015/05/19.
// Copyright (c) 2015年 masai. All rights reserved.
//
#include <iostream>
#include <limits>
typedef long HashValueLong;
typedef unsigned long HashValueULong;
int main(int argc, const char * argv[]) {
// マクロ定義による取得
std::cout << "int max: " << INT_MAX << std::endl;
std::cout << "int min: " << INT_MIN << std::endl;
// クラステンプレートによる取得
std::cout << "int max: " << std::numeric_limits<int>::max() << std::endl; //2147483647
std::cout << "long max: " << std::numeric_limits<long>::max() << std::endl; //2147483647
// 型に依存しない書き方
std::cout << "HashValue(long): " << std::numeric_limits<HashValueLong>::max() << std::endl;
std::cout << "HashValue(unsigned long): " << std::numeric_limits<HashValueULong>::max() << std::endl;
return 0;
}
view raw limits.cpp hosted with ❤ by GitHub

参考サイト
C++のプリミティブ型が取りうる最大値を取得する。
https://www.c3.club.kyutech.ac.jp/archives/1203

0 件のコメント:

コメントを投稿