Overloading Present for multiple arguments - fortran

Is it possible to overload Present(arg) so I can have
Present(arg1,arg2,...) to mean
If (Present (arg1) .And. Present (arg2) .And. ... )
I am trying to do it but it feels as though it is not so straightforward to do.

Interestingly the answer is: no, you cannot. You can indeed create a generic identifier called present and have a new specific name:
module mod
interface present
module procedure present_two_real
end interface
contains
logical function present_real_real(a,b)
..
end function
end module
However, inside that function we know that the dummy arguments must be optional. If they weren't it wouldn't be legal to pass optional actual arguments in a procedure to that function: see Fortran 2008 12.5.2.12.
When we look at how we different two procedures must be to be able to have the same generic identifier (12.4.3.4.5) we have constraint C1215. It's this constraint with the optional requirement in the new specific name which makes us unable to do what you want. Note that the argument in the specific procedure present isn't optional.
That doesn't mean you can't have a generic present_all, of course. You'll need a specific procedure for each combination of argument characteristics you want, though (as my choice of specific name above suggests). [Recall that template's are not in Fortran's style.] Further, you'll still need to handle the requirement to distinguish the specific implementations. It all sounds like a bit too much work, really.

Related

How to make CPP core functions friends of my class

Help me please. I want to make my class for range statement compliant. That means I need the required overloaded operators defined and define begin and end functions.
What I don't want is for anything else except for range to be able to use the defined begin and end functions . Simply because it wouldn't be needed otherwise.
How can I make range for statement a friend of my class?
It’s not possible to restrict the use of begin/end to the range-for statement, since it is defined as equivalent to a certain compound statement that looks them up without any special access permission. The closest you can get is to make them hidden friends, but that doesn’t hide them when their argument is of the class type in question!

Same block of code in a SELECT TYPE in Fortran

I’m wondering if there is an elegant way to avoid repeating block of code that apply to different types in a SELECT TYPE construct. Consider for example:
select type (var)
type is (t1_t)
codeA (many lines of code)
type is (t2_t)
codeA (same lines)
...
type is (tn_t)
codeB
class default
codeC
end select
Unlike the select case construct, where you can group multiple tests in the same case satement, there is no such facility in the select type construct.
The reason is: within the block of each type-guard statement, the selector (variable or expression you're matching) will have the same type as named in the type-guard statement, and won't be polymorphic there. This is how you can have dynamic type resolution in Fortran, that is statically typed.
select type (var)
type is (t1_t)
! Here, type of var is t1_t, and you can call
! procedures that use type(t1_t) as arguments with var
type is (t2_t)
! Here, type of var is t2_t, and procedures expecting
! type(t1_t) as arguments won't work with var
...
end select
Therefore, compiler can't allow you to group many types in the same type-guard, because it would't know which dynamic type to apply on the selector.
As a side note, unlike switch satement in c-derived languages, select constructs in Fortran do not fall through, i.e., after a match in Fortran, the corresponding block is executed and the control exits the construct.
As #cup said, you can convert whatever you have in common on the various branches in a subroutine in order to avoid repetition. But be aware that if you need to pass var to the routine, you must declare it as polymorphic dummy.
As francescalus pointed out in the comments, the typical way to repeat the same lines of code is to use an include file. This is a traditional technique which used to be widely used for common blocks and is also used for poor-man's templating.
included.f90:
codeA (many lines of code)
main.f90:
select type (var)
type is (t1_t)
include "included.f90"
type is (t2_t)
include "included.f90"
...
end select
If you use the C preprocessor, you can use the preprocesor's #include as well.
There is the overloaded operator type of construct that the 'type is' suggests. That needs to be in a module as a subroutine or function. I mostly use functions, so if one is mixing with C, then subroutines may be easier than a function trying to return a vector.
It will still be the same exact code, just operating on a complex, float, double, or variety of integer but depths... so there is no explicit 'type of' as the right version is selected based upon the arguement types.

How to read number of arguments - c++

Usually in my code I need to use specific functions for various variables i.e.
object->SetStatus("var1",1); object->SetAddress("var1",&var1);
object->SetStatus("var2",1); object->SetAddress("var2",&var2);
object->SetStatus("var3",1); object->SetAddress("var3",&var3);
...
My idea is to use a function that will do this automatically by calling it, i.e.
object->function(var1,var2,var3,...);
To achieve that I have to solve 3 issues
I need to read the number of arguments when calling function()
I need to parse somehow the argument names inside the code
Since the variables are not of the same type, I need to find a way to make function() type "transparent"
Since I am newbie in c++ coding, I tried to search fo something similar, but I couldn't find anything.
Any help, advice or remark is more than welcome!
There are multiple ways to do so. One way is make a Base class and all your variable type will inherit from this base class. Then pass a map<string,Base> as an argument to you function. name of variable will be key and value will be actual variables. Iterate through the map and set and assign values to methods.
You could consider some variadic template, if coding in C++11 or C++14. There is considerable literature about that subject (e.g. this tutorial), which is a bit tricky (so explaining it here is not reasonable). Read also about parameter pack
You could also use C style varargs using <cstdarg>
Perhaps std::initializer_list could be useful too.

Is there a standard way of determining the number of va_args?

I'm experimenting with variable arguments in C++, using va_args. The idea is useful, and is indeed something I've used a lot in C# via the params functionality. One thing that frustrates me is the following excerpt regarding va_args, above:
Notice also that va_arg does not determine either whether the retrieved argument is the last argument passed to the function (or even if it is an element past the end of that list).
I find it hard to believe that there is no way to programmatically determine the number of variable arguments passed to the function from within that function itself. I would like to perform something like the following:
void fcn(int arg1 ...)
{
va_list argList;
va_start(argList, arg1);
int numRemainingParams = //function that returns number of remaining parameters
for (int i=0; i<numRemainingParams; ++i)
{
//do stuff with params
}
va_end(argList);
}
To reiterate, the documentation above suggests that va_arg doesn't determine whether the retrieved arg is the last in the list. But I feel this information must be accessible in some manner.
Is there a standard way of achieving this?
I find it hard to believe that there is no way to programmatically determine the number of variable arguments passed to the function from within that function itself.
Nonetheless, it is true. C/C++ do not put markers on the end of the argument list, so the called function really does not know how many arguments it is receiving. If you need to mark the end of the arguments, you must do so yourself by putting some kind of marker at the end of the list.
The called function also has no idea of the types or sizes of the arguments provided. That's why printf and friends force you to specify the precise datatype of the value to interpolate into the format string, and also why you can crash a program by calling printf with a bad format string.
Note that parameter passing is specified by the ABI for a particular platform, not by the C++/C standards. However, the ABI must allow the C++/C standards to be implementable. For example, an ABI might want to pass parameters in registers for efficiency, but it might not be possible to implement va_args easily in that case. So it's possible that arguments are also shadowed on the stack. In almost no case is the stack marked to show the end of the argument list, though, since the C++/C standards don't require this information to be made available, and it would therefore be unnecessary overhead.
The way variable arguments work in C and C++ is relatively simple: the arguments are just pushed on the stack and it is the callee's responsibility to somewhat figure out what arguments there are. There is nothing in the standard which provides a way to determine the number of arguments. As a result, the number of arguments are determined by some context information, e.g., the number of elements referenced in a format string.
Individual compilers may know how many elements there are but there is no standard interface to obtain this value.
What you could do instead, however, is to use variadic templates: you can determine very detailed information on the arguments being passed to the function. The interface looks different and it may be necessary to channel the arguments into some sort of data structure but on the upside it would also work with types you cannot pass using variable arguments.
No, there isn't. That's why variable arguments are not safe. They're a part of C, which lacks the expressiveness to achieve type safety for "convenient" variadic functions. You have to live with the fact that C contains constructions whose very correctness depends on values and not just on types. That's why it is an "unsafe language".
Don't use variable arguments in C++. It is a much stronger language that allows you to write equally convenient code that is safe.
No, there's no such way. If you have such a need, it's probably best to pack those function parameters in a std::vector or a similar collection which can be iterated.
The variable argument list is a very old concept inherited from the C history of C++. It dates back to the time where C programmers usually had the generated assembler code in mind.
At that time the compiler did not check at all if the data you passed to a function when calling it matched the data types the function expected to receive. It was the programmer's responsibility to do that right. If, for example, the caller called the function with a char and the function expected an int the program crashed, although the compiler didn't complain.
Today's type checking prevents these errors, but with a variable argument list you go back to those old concepts including all risks. So, don't use it if you can avoid it somehow.
The fact that this concept is several decades old is probably the reason that it feels wrong compared to modern concepts of safe code.

Is there any way to programmatically determine in C/C++ how many parameters a Lua function expects?

Is there a way to determine how many parameters a Lua function takes just before calling it from C/C++ code?
I looked at lua_Debug and lua_getinfo but they don't appear to provide what I need.
It may seem a bit like I am going against the spirit of Lua but I really want to bullet proof the interface that I have between Lua and C++. When a C++ function is called from Lua code the interface verifies that Lua has supplied the correct number of arguments and the type of each argument is correct. If a problem is found with the arguments a lua_error is issued.
I'd like to have similar error checking the other way around. When C++ calls a Lua function it should at least check that the Lua function doesn't declare more parameters than are necessary.
What you're asking for isn't possible in Lua.
You can define a Lua function with a set of arguments like this:
function f(a, b, c)
body
end
However, Lua imposes no restrictions on the number of arguments you pass to this function.
This is valid:
f(1,2,3,4,5)
The extra parameters are ignored.
This is also valid:
f(1)
The remaining arguments are assigned 'nil'.
Finally, you can defined a function that takes a variable number of arguments:
function f(a, ...)
At which point you can pass any number of arguments to the function.
See section 2.5.9 of the Lua reference manual.
The best you can do here is to add checks to your Lua functions to verify you receive the arguments you expect.
You can determine the number of parameters, upvalues and whether the function accepts variable number of arguments in Lua 5.2, by using the 'u' type to fill nups, nparams, isvararg fields by get_info(). This feature is not available in Lua 5.1.
I wouldn't do this on the Lua side unless you're in full control of Lua code you're validating. It is rather common for Lua functions to ignore extra arguments simply by omitting them.
One example is when we do not want to implement some methods, and use a stub function:
function do_nothing() end
full_api = {}
function full_api:callback(a1, a2) print(a1, a2) end
lazy_impl = {}
lazy_impl.callback = do_nothing
This allows to save typing (and a bit of performance) by reusing available functions.
If you still want to do function argument validation, you have to statically analyze the code. One tool to do this is Metalua.
No, not within standard Lua. And is Aaron Saarela is saying, it is somewhat outside the spirit of Lua as I understand it. The Lua way would be to make sure that the function itself treats nil as a sensible default (or converts it to a sensible default with something like name = name or "Bruce" before its first use) or if there is no sensible default the function should either throw an error or return a failure (if not name then error"Name required" end is a common idiom for the former, and if not name then return nil, "name required" end is a common idiom for the latter). By making the Lua side responsible for its own argument checks, you get that benefit regardless of whether the function is called from Lua or C.
That said, it is possible that your modules could maintain an attribute table indexed by function that contains the info you need to know. It would require maintenance, of course. It is also possible that MetaLua could be used to add some syntax sugar to create the table directly from function declarations at compile time. Before calling the Lua function, you would use it directly to look up any available attributes and use them to validate the call.
If you are concerned about bullet-proofing, you might want to control the function environment to use some care with what (if any) globals are available to the Lua side, and use lua_pcall() rather than lua_call() so that you catch any thrown errors.
The information you ask for is not available in all cases. For example, a Lua function might actually be implemented in C as a lua_CFunction. From Lua code there is no way to distinguish a pure Lua function from a lua_CFunction. And in the case of a lua_CFunction, the number of parameters is not exposed at all, since it's entirely dependent on the way the function is implemented.
On the other hand, what you can do is provide a system for functions writers (be it in pure Lua or in C) to advertise how many parameters their functions expect. After creating the function (function f(a, b, c) end) they would simply pass it to a global function (register(f, 3)). You would then be able to retrieve that information from your C++ code, and if the function didn't advertise its parameters then fallback to what you have now. With such a system you could even advertise the type expected by the parameters.