1

これは重複している必要があるように感じますが、どこにも見つからないようで、非常に迅速なグーグル検索では何も得られませんでした。

モジュール内のものの名前を変更して、ローカル(またはグローバル)の名前と競合しないようにする方法はありますか?例を考えてみましょう。

module namespace
   real x  !some data
   contains
   subroutine foo()
     write(0,*) "foo!"
   end subroutine foo
end module
subroutine foo()
   write(0,*) "foo is the new bar :)"
end subroutine

program main
  use namespace
  real x
  call foo() !should print "foo is the new bar"
  call namespacefoo() !somehow call module namespace's version of foo
end program main

上記のコードは、xが定義されていないためコンパイルされません。もちろん、という名前のローカル変数が必要ない場合はx可能use namespace, only: fooですが、ローカル変数名を壊さなければならないのは少し面倒なようです。(補足として、私はこれを以前に見たことがあると確信していますonlyが、ステートメントの一部にいくつかの魔法があります...)


Pythonも知っている人のために、Pythonに似たものを探しています。

import namespace as other_namespace

または、Fortranにはそのレベルの名前空間制御がないため、次のように推測します。

from namespace import somefunc as otherfunc
from namespace import somedata as otherdata
4

2 に答える 2

4

名前を変更する必要があります:

[luser@cromer stackoverflow]$ cat ren.f90
module namespace
   real x  !some data
   contains
   subroutine foo()
     write(0,*) "foo!"
   end subroutine foo
end module
subroutine foo()
   write(0,*) "foo is the new bar :)"
end subroutine

program main
  use namespace, local_name => x, namespacefoo => foo  
  real x
  call foo() !should print "foo is the new bar"
  call namespacefoo() !somehow call module namespace's version of foo
end program main
[luser@cromer stackoverflow]$ nagfor ren.f90
NAG Fortran Compiler Release 5.3.1 pre-release(904)
Warning: ren.f90, line 17: X explicitly imported into MAIN (as LOCAL_NAME) but not used
Warning: ren.f90, line 17: Unused local variable X
[NAG Fortran Compiler normal termination, 2 warnings]
[luser@cromer stackoverflow]$ ./a.out
 foo is the new bar :)
 foo!

もちろん、この種のことを正確に回避するために、可能であれば、モジュールに対して物事を非公開にしておくことをお勧めします。

于 2013-01-11T13:42:32.117 に答える
0

私のグーグル検索でもっと一生懸命に見えるべきだったようです:

use namespace, only: namespace_x => x, namespacefoo => foo

ローカル名前空間のようxに、ローカル名namespace_xと名前空間のサブルーチンの下に名前空間を「インポート」します。foonamespacefoo

他の人の利益のためのいくつかのコード:

module namespace
   real x  !some data
   real y
   contains
   subroutine foo()
     write(0,*) "foo!"
   end subroutine foo
end module

subroutine foo()
   use namespace, only: x,y
   write(0,*) "foo is the new bar :)"
   write(0,*) "by the way, namespace.x is:",x
   write(0,*) "by the way, namespace.y is:",y
end subroutine

program main
  use namespace, only: namespacefoo => foo, y, z => x
  real x
  x = 0.0
  y = 1.0
  z = 2.0
  call foo() !should print "foo is the new bar"
  call namespacefoo() !somehow call module namespace's version of foo
end program main
于 2013-01-11T13:40:03.160 に答える