Hi Sebastian, welcome to this forum.
As @han190 pointed out, the issue in your original code the operator(-)
is bound to the type(vector)
. I suggest to read carefully the link he shared.
As for your problem, I don’t know what you actually want to achieve, but from what I could infer, you might find interesting this variant, which removes entirely the extending type(vector_parameter)
:
module mo_vec
type, public :: vector
real :: x, y
end type vector
interface operator(-)
module procedure diff
module procedure neg
end interface
interface vector
procedure init_vec
end interface vector
contains
! NOTE: this is what the compiler already provides you in any case.
! WHICH IS THE ONLY CONSTRUCTOR YOU CAN CALL IN A CONSTANT EXPRESSION
elemental pure type(vector) function vector_as_comp(x, y)
real, intent(in) :: x, y
vector_as_comp%x = x
vector_as_comp%y = y
end function vector_as_comp
! Your custom defined vector constructor
elemental pure type(vector) function init_vec(x, y, factor)
real, intent(in) :: x, y, factor
real :: x_, y_
x_ = x * factor
y_ = y * factor
init_vec = vector(x_, y_)
end function init_vec
pure type(vector) function diff(this, that)
class(vector), intent(in) :: this, that
diff = vector(this%x-that%x, this%y-that%y)
end function diff
pure type(vector) function neg(this)
class(vector), intent(in) :: this
neg = vector(-this%x, -this%y)
end function neg
end module mo_vec
program vec_test
use mo_vec
implicit none
type(vector), parameter :: vec_x = vector(1., 0.)
type(vector), parameter :: vec_y = vector(0., 1.)
print *, vec_x - vec_y
print *, vec_x - -vec_y
print *, vector(1., 2., 5.)
end program vec_test
Basically, you simply make use of the default constructor that the compiler “writes” for you. Which in Fortran is the only one constructor you can use when default constructing a variable.
PS: of course, you could entirely remove the procedure vector_as_comp
, it is there just as a matter of example.