I wish there were a guide to modern C++ for modern Fortran programmers that discussed analogous concepts. It could programmers moving in either direction. I don’t know C++ well, but here are a few thoughts. There was a previous thread Fortran for C++ programmers ... guidelines?.
C++ now has modules, so you no longer need to write and #include header files.
C++ functions can declared constexpr, which remind me of pure functions in Fortran.
C++ functions can have const arguments, which can be intent(in) in Fortran.
C++ auto has type inference, similar to associate in Fortran.
C++ variables declared within braces have scope within those braces, similar to variables defined within block, end block in Fortran.
Here is a trivial C++ code using modules, followed by a Fortran analog.
math.cpp
export module math;
export constexpr int cube(const int n){
return n*square(n);
}
// square() is not exported but can be used within module
constexpr int square(const int n){
return n*n;
}
main.cpp
#include <iostream>
import math;
int main(){
const auto n = 4;
// line below invalid since square does not have export
// attribute in module math
// std::cout << "square of " << n << " is " << square(n) << "\n";
std::cout << "cube of " << n << " is " << cube(n) << "\n";
}
compile with g++ -fmodules-ts math.cpp main.cpp
Fortran
module math
implicit none
private
public :: cube
contains
pure function cube(n)
integer, intent(in) :: n
integer :: cube
cube = n*square(n)
end function cube
!
! square() is not exported but can be used within module
pure function square(n)
integer, intent(in) :: n
integer :: square
square = n**2
end function square
end module math
!
program main
use math
implicit none
! line below invalid because square is not public in module math
! print*,"square of ",n," is",square(n)
associate (n => 4)
print*,"cube of ",n," is",cube(n)
end associate
end program main