p_tan's blog

勉強日記です。ツッコミ大歓迎

整数型か浮動小数型かで四捨五入するかどうか分岐する関数テンプレート

こんな関数テンプレートがあったら使い所があるかも。

#include <cassert>

// RetTypeが整数型の場合は四捨五入した値を返し、
// RetTypeが浮動小数型の場合はそのままの値を返す。
template<typename RetType, typename ArgType>
RetType IfIntegralThenRound(ArgType val)
{
	return static_cast<RetType>(val + 0.5) - static_cast<RetType>(0.5);
}

int main()
{
	assert(0.5 == IfIntegralThenRound<double>(0.5));
	assert(10e+100 == IfIntegralThenRound<double>(10e+100));
	assert(3.15e+17 == IfIntegralThenRound<double>(3.15e+17));
	assert(1 == IfIntegralThenRound<int>(1.4));
	assert(2 == IfIntegralThenRound<int>(1.5));
	assert(3000001 == IfIntegralThenRound<int>(3000000.5));
	return 0;
}

ただし、キャスト後の値がオーバーフローとかしないことが前提。