Fortran での operator overload
Fortran90 で、単項演算子および二項演算子に対して、演算子オーバーロードが定義できるようになりました。組み込み型の単項演算子・二項演算子に対しては、組み込み型ですでに定義されている被演算子の型とダブらない必要があります。それは区別がつかなくなるためだと思います。
では、どのような組み込み型演算子に対してオーバーロードできるのか探してみました。素朴に考えて、正負の符号を与える単項演算子と加減乗除の二項演算子が思いつきます。このほかにべき乗の ** や、文字列結合の // も二項演算子としてオーバーロードできます。また、≧,≦,>,<,==,/= のような比較演算子や論理演算の二項演算子もオーバーロードできます。
単項演算子には、他に論理型を否定する .not. 演算子がありますが、前後に . の付いた演算子は、自由に定義できるので、それほど意味も無かろうかと思います。
演算子にはまだ見落としがあるかもしれません。
なおこれに加えるに、代入演算子 = もオーバーロードできます。
ソース・プログラム
module m_mod
implicit none
! binary / dyadic
interface operator (>=) !.ge.
module procedure op2
end interface
interface operator (>) !.gt.
module procedure op2
end interface
interface operator (<=) !.le.
module procedure op2
end interface
interface operator (<) !.lt.
module procedure op2
end interface
interface operator (==) !.eq.
module procedure op2
end interface
interface operator (/=) !.ne.
module procedure op2
end interface
interface operator (//)
module procedure op2
end interface
interface operator (**)
module procedure op2
end interface
interface operator (.and.) !.or. .eqv. .neqv.
module procedure op2
end interface
! unary / monadic
interface operator (.not.)
module procedure op1
end interface
interface operator (+)
module procedure op1
end interface
interface operator (-)
module procedure op1
end interface
contains
pure integer function op2(c1, i)
character, intent(in) :: c1
integer , intent(in) :: i
op2 = iachar(c1) + i
end function op2
pure integer function op1(c1)
character, intent(in) :: c1
op1 = iachar(c1)
end function op1
end module m_mod
program hello
use m_mod
implicit none
! print *, 'c' >= 5, .not.'a'
print *, .not. 'a'
print *, +'b'
print *, -'c'
end program hello
実行結果
97
98
99
続行するには何かキーを押してください . . .