2

采取诸如

function c(a,b)
  integer,parameter        :: dp=kind(2.0e0) 
  real(kind=dp),intent(in) :: a,b
  real(kind=dp)            :: c
  c=a+b
end function

有没有办法在同一个程序中调用不同种类的同一个函数?例如:

program help
  integer,parameter    :: sp=kind(2.0d0),dp=kind(2.0e0) 
  print *, c(2.0_dp,3.0_dp)
  print *, c(2.0_sp,3.0_sp)
end program

我知道我可以c使用sp参数再次编写函数并提供一个将两者合二为一的界面,但我正在寻找一种不需要创建另一个函数的解决方案......可能只是修改现有的?

4

1 回答 1

6

No, there is no way to write a function that accepts arguments of the different kinds of real (or any of the other intrinsics). As you already know, the standard way to write code which is kind-indifferent is to write implementations for each of the kinds you are concerned with and to wrap them in an interface.

You could, if you prefer something more kludgy, write a routine for low-precision kinds which wraps a call to the matching routine for high-precision kinds and incorporates some kind adjustment. Personally I prefer the interface route to this.

Finally, you may well find that your compiler allows you to get away with passing arguments of the wrong kind to a routine, performing some automatic kind adjustment behind the scenes. This is non-standard and likely to be non-portable.

于 2013-05-05T17:57:31.473 回答