pointers,generics,fortran , Generic name for distinguishable pointers

Generic name for distinguishable pointers


Tag: pointers,generics,fortran

Is it possible to use the same generic name for two pointers of different type? The following of course doesn't work, but it should make clear what I mean:

real(4), pointer :: s_p
real(8), pointer :: d_p
generic :: p => s_p,d_p

For procdures these things can be done with interfaces defining destinguishable procedures as module procedure and for type bound procedures there exists the generic type that is used similar to the given example. So I wonder if something like this exists for pointers too.

I'd like to mention that unlimited polymorphic pointers (class(*)) are probably not what I want, since I'm trying to generalize an existing library to double precision input, thus I'd have a lot more work in implementing the select type blocks than just defining two pointers everywhere.


It is of course possible to associate the same pointer with variables of different type/kind. Just some examples:

program test

   implicit none
   real(4),target :: a
   real(8),target :: b
   class(*),pointer :: p


   call printer(p)
   call printer(p)
   call printer(p)

   associate (u=>a)       ! for me it's still a miracle why this even works
   end associate
   associate (u=>b)
   end associate


   subroutine printer(p)

      class(*),pointer :: p

      select type (p) 
      type is (real(4))
         p=p+2d0              ! even the wrong 2d0 gets converted correctly
      type is (real(8))
      end select

   end subroutine

end program

My problem with this solution is that I would have to implement select type blocks everywhere in the library where the pointer is used. (At the moment I only know that it's many places.)

So the main problem is that the unlimited polymorphic pointer (p in the example) stays polymorphic unless it is used inside a select type environement. This is of course necessary, since the pointer could be everything. So the actual question is: Is there a possibility to tell the polymorphic pointer in advance: You can only be either this or that (e.g real(4) or real(8)) and depening on what it is associated to, it knows what it is?

The answer is probably no, but at the moment I don't really see, in which situtation the compliler might have problems to distinguish between types/kinds.


No. A data pointer is a variable. You cannot have two different variables with the same name accessible in the same scope.

If you hypothetically could... in many cases the compiler would have no way of knowing which variable you meant when that common name appeared.

The situation for generic procedure names is different - the compiler can resolve which specific procedure is relevant when a generic procedure name is referenced by examining the number, types, kinds and ranks of the arguments in the procedure reference. The rules of the language ensure that there can only be at most one such matching specific procedure, and that generic procedure names do not appear in contexts where the ability to resolve the relevant specific procedure is not possible.


passing arguments via reference and pointer C++

I am looking at a code snippet and I have this sequence. class MyVariable { .... CustomType z; .... } A.cpp calling a function f ( & myVariable) In an included file I do have this : B.h void f ( MyVariable * myVariable); B.cpp f( MyVariable * myVariable){ CustomType...

How can I pass N number of generic arguments to a typedef function pointer?

I have this typedef function pointer plot: typedef void(*plot)(); How can I pass a generic argument to it (Something like this): template<typename T> typedef void(*plot)(T); And then, how can I pass N number of generic arguments to it? template<typename T> typedef void(*plot)(T ...); ...

Can assignment from a const_iterator dereference cause undefined behaviour?

This code is a simplified test for something I am trying to do for real elsewhere. I have a function which takes a "ref-to-ptr" argument and modifies it to return a pointer from a list of pointers. #include <iostream> #include <list> using namespace std; typedef int* intp; typedef std::list<intp> intplist;...

Function pointer to singleton class instance function

What I'm trying to do is create a function pointer to a single class instance function. I want to do this so I can do something like this: C->member_method(); instead of: Config::inst()->member_method(); but I'm not sure how to go about it. Here is my singleton class: class Config { private:...

Creating a generic / abstract “DBContext” Class for shared functionality among different DBs

I am working on a C# project that is pulling data from SQL Server, ODBC data-sources and Oracle Databases at different times. At this point, I have created 3 different classes - Once for each type of DB access. However, I am seeing that 95% of the code is identical...

Spring, Java : Passing Generic object List as return type

I am working on a Spring-MVC application in which depending upon the mode set by the user, I have to return a List of either Object1 or Object2. Ideally, I can create two controller methods and send the List appropriately, but I would like to know is there any way,...

Swift generic constructor

The questions are embedded in comments as well as here: How can I define a default value for a generic T in parameter list? When copying a parameter in Swift, is it pointers or objects? XCode Beta 7 tells me I can't change "head", as it is a "let", see...

Java Generic type is failing without an intermediate variable

I'm having an unexpected error while compiling this example code (in the fails() method). IntelliJ used to not report the error in the IDE, but it has since started to report it (some of the classes were in a library, which seemed to confuse it) public class Main { //...

Generic TypeCode Type Checking?

Should I avoid type checking with generics? Not using traditional type checking comparisons(myvar is int), but rather using the type's typecode. Using generics, with type checking allows you to create a single method without parameters that supports the tasks of regular overloaded methods. This is a problem with parameter-less methods,...

Using [] on pointers in C?

Right now I'm looking over some C code and they have some pointer syntax that I'm confused about. So first they declared a pointer like so: int32_t *p_tx_buf=NULL; Then later on they wrote: p_tx_buf = malloc(...math... ); The stuff in the middle is just math to calculate the size of...

create ndarray out of c++ pointer

I created a module in c++ and need to use the results in python. Already wrote a wrapper and it is working with this code a = np.empty([r, hn]) for i in xrange(r): for j in xrange(hn): a[i,j]=self.thisptr.H[i*hn+j] return a The code is working, but I think there should be...

How to create generic convenience initializer in Swift?

I'm tackling with generics in Swift. I've got extension to NSManagedObject class and wanted to create initializer which is only available for classes which implements some protocol I defined. Now I've got something like below but this is not working and even not compiling. Could you help me make it...

Ninject generic type xml binding

I need to bind generic interface with generic implementation using Ninject.Extensions.Xml. The project is .net mvc project. Is there any way to accomplish this ? The class: public class JsonProvider<T> : IJsonProvider<T> where T: new() { ... } Xml configuration (Not working): <bind service="Base.IJsonProvider, Base" to="Base.JsonProvider, Base" name ="Config"/> ...

How can I find out the Objective-C generics type?

Xcode 7 contains an Objective-C variant, where you can define a type-hint for (homogenous) NSArray return values and properties, defined such as NSArray<UIImage*>. I'd like to use this feature to rewrite my JSON-deserializer class (which needs such kind of type hints – previously I have solved this by adding a -(Class)jsonHintForKey:(NSString*)key...

modifying double pointer to an integer array

void function(int **arr); int main() { int *array; array=calloc(4, sizeof(int)); function(&array); return0; } void function(int **arr) { int *tmp; tmp=calloc(4, sizeof(int)); tmp[0]=1; tmp[1]=2; tmp[2]=3; tmp[3]=4; } I want to assign tmp to arr. how can I do it?...

Although maps are always reference types, what if they're returned from a non-pointer receiver?

Supposedly maps are reference types in Go, so when returning them from functions, you don't need to pass as a pointer to the map in order for the changes to be visible outside the function body. But what if said map is returned from a method on a non-pointer struct?...

Set only second argument type in generic method

I have to create a method for selecting a firts property from collection with the specified type. I have created the method like this (I have removed some parts for the brevity): public static IQueryable<TResult> SelectFirstPropertyWithType<T, TResult>(this IQueryable<T> source) { // Get the first property which has the TResult type...

Program to reverse a string in C without declaring a char[]

I need to reverse a given string and display it without using the value At[index] notation , I tried the below program using pointers,but it does not print anything for the reverse string, Please help! int main() { char* name=malloc(256); printf("\nEnter string\n"); scanf("%s",name); printf("\nYou entered%s",name); int i,count; count=0; //find the...

How to pass pointer to struct to a function?

I am instantiating the struct within the main() function and I am passing a pointer to this structure over to a function. I would like to then pass this pointer to the original struct to another function, how would I do this? I am now lost in pointerception. struct coords...

Why is generic of a return type erased when there is an unchecked conversion of a method parameter in Java 8?

Consider the following code sample: import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) { List list = new ArrayList<Integer>(); String response = getProducer(list).get(); } static Producer<String> getProducer(List<Integer> list) { return new Producer<String>(); } } class Producer<T> { T get() { return null; } } When...

How to compose two lambdas of type “delegate” in c#

Lets assume we have defined two Lambdas. Func<TInput, TOutput> a = …; Func<TInput1, TInput2, TOutput> b = …; Now lets assume that we have some code that does not work with generics and receives these Lambdas as not further typed delegates. delegate da = a; delegate db = b; In...

Parameters to use in a referenced function c++

I am very confused as to what kind of variables I would put into my function here: names. I am doing a practice problem in a C++ book, because I am learning C++ and am on References and pointers right now, and cannot find a solution. Just for background information,...

Print addresses of all local variables in C

I want to print the addresses of all the local and global variables which are being used in a function, at different points of execution of a program and store them in a file. I am trying to use gdb for this same. The "info local" command prints the values...

Difference between the use of pointers for array and single data point?

#include <iostream> using namespace std; const int MAX = 3; int main () { int var[MAX] = {10, 100, 200}; int *ptr; // let us have array address in pointer. ptr = var; for (int i = 0; i < MAX; i++) { cout << "Address of var[" << i...

Generic method only compiles with one argument

The below code will not compile, it says that the method is not applicable for the arguments. The interesting thing is that if I remove one of the arguments (doesn't matter which) then it compiles fine. public class Test1 { static Collection<? extends Shape> someColl = new ArrayList<Shape>(); public static...

converted string failed to contain correct values of float

I am facing problem in converting float to char*. I have written a function that will put integer part of float in string and then decimal values. I need it for two places of decimal. But something is horribly wrong. Either it ouputs integer value or just 1 place after...

pointer to pointer dynamic array in C++

I've been having bad luck with dynamic pointers when I want to close it. why the application wrote to memory after end of heap buffer? how can I close my array? int main() { . . int **W; W = new int* [n]; for (int i=1; i <= n; i++)...

How to code a generic Swift class which stores a Generator of the same type

I'm trying to write a class which handles objects of a homogenous type, and I'd like to feed in those objects using an (otherwise arbitrary) Generator of the same type. In essence this: class MyGenericClass<T> { var source : GeneratorType var itemsProcessed = [ T ]() init(source: GeneratorType) { self.source...

Resolving Interface with generic type constraint with Castle Windsor

Given the interface where FooRequest and FooResponse are abstract: public interface IFooHandler<TRequest, TResponse> where TRequest : FooRequest where TResponse : FooResponse { TResponse CheckFoo(TRequest request); } An implementation of: public class MyFooHandler : IFooHandler<MyFooRequest, MyFooResponse> { public MyFooResponse CheckFoo(MyFooRequest request) { /* check for foos */ } } How would...

Does realloc() invalidate all pointers?

Note, this question is not asking if realloc() invalidates pointers within the original block, but if it invalidates all the other pointers. I'm new to C, and am a bit confused about the nature of realloc(), specifically if it moves any other memory. For example: void* ptr1 = malloc(2); void*...

Under Xcode 6.3, NULL C++ reference address evaluates as non-zero

Similar to this question: XCode 6.3 Warning : Comparison of address of 'myObject' not equal to null pointer is always true with C++, I found that previously working code for evaluating null pointers stopped working: struct AStruct { int x, y; char *name; }; AStruct& GetStruct() { return *(AStruct*)0; }...

memory content not erased after deleting my pointer (on a simple example) [duplicate]

This question already has an answer here: Can a local variable's memory be accessed outside its scope? 16 answers Here is a simple of example of a question I have: I create a pointer of integer (value 5), I print the pointer (hence the address) of the memory case...

Register return Type

We have a C# class that holds session values for user in an MVC web application. Now I want to make the class more generic. Until now we have getters and setters for the session like public class WebAppLogin { public static WebAppLogin Current { get; //Gets the current Login...

Functions with pointer arguments in C++

I'm having some difficulties in understanding some aspects of functions with pointers. Here is the code I'm running: #include <iostream> using namespace std; class Item { public: Item(Item * it) { data = it->data; } Item(int d) { data = d; } void printData() { cout << data << endl;...

Why does adding a parameterless constructor to my entity model class work here? What are the implications?

So I have this office entity class: [Table("office_entity")] public class EFOffice : EFBusinessEntity { [Column("address")] [StringLength(250)] public string Address { get; set; } [Column("business_name")] [StringLength(150)] public string BusinessName { get; set; } public virtual ICollection<EFEmployee> Employees { get; set; } public EFOffice(Guid id, Guid tenantId, string address, string businessName) {...

Pointer parameter was set but never used warning

I have the following function: void foo(char *ptr_1) { char *ptr_2; bar(ptr_2); ptr_1 = ptr_2; } And get this warning: parameter "ptr_1" was set but never used I understand that the warning is technically true, but is irrelevant at the same time. I could suppress it with: (void)(ptr_1) But is...

Why does this extension method not initialize the returned object?

I wrote a generic Extension helper method to initialize some parameters of a SoapHeader, however it is not updating the returned object. What am I missing? using System.Web.Services.Protocols; public class Header: SoapHeader {} public class WS { public Header securityHeader { get; set; } } public static class SecurityHeaderExtensions {...

function pointer is not a function or function pointer

I have following problem: void MyClass::LoopFunction(vector<Item>& items,void (MyClass::*funcy)(vector<Item>&,int)) { for(SInt32 i = 0; i < 50; i++) { funcy(items,i); } } It says: Called object type 'void(MyClass::*)(vector<Item>&,int)' is not a function or function pointer Can anyone help me to find a solution for this?...

binary tree code does not work properly

I made a tree structure, read words from file and registered them to the tree. But the enter() does not work properly. I debuged with gdb and set a break point line 42. Then I entered print *node print *root. (gdb) print node $9 = (struct node *) 0x603250 (gdb)...

Allocate a new bool array pointer

I'm curious how you go about allocating a new boolean array pointer in c++. I did some looking around but couldn't find anything that is similar to how I've learned to allocate new pointers. To allocate a new int pointer I have learned to do int * intPointer = new...

Using a Type Variable in a Generic

I have this question except for Swift. How do I use a Type variable in a generic? I tried this: func intType() -> Int.Type { return Int.self } func test() { var t = self.intType() var arr = Array<t>() // Error: "'t' is not a type". Uh... yeah, it is....

Why can't I use `&&a` in C?

int main(int argc, char * argv[]) { int a = 10; int * sp = &a; int * * dp1 = &sp; int * * dp2 = &&a; // NG int * * dp3 = &(&a); // NG int * * dp4 = &((int *) &a); // NG } $...

Passing iterator's element to a function: wrong type of pointer

I'm attempting to solve Project Euler's problem #3 using C++ to gain an understanding of how to use C++ iterators. According to the examples I've seen online, I can use the dereferened iterator as a parameter for cout, and it will print the elements successfully. By that same logic, I...

Access violation on try to fill dynamic array (large number of items)

I have the following C code: int dimension; double *AtS; ... AtS=(double*)malloc(sizeof(double)*dimension); for (i=0; i<dimension; i++) { AtS[i]=0.0; } While dimension is ~6-8 millions it works fine, but when it about 300 millions it fails with access violation. The following message in debug: Unhandled exception at 0x012f1077 in mathpro.exe: 0xC0000005:...

Call template function for the value of a pointer out of a template function, in C++

I am trying to call a template function for the pointer that was given as template parameter in my calling function. My code is: template <> struct serialize_helper<std::string> { // not important code... } }; template <class T> inline void serializer(const T& obj, StreamType::iterator& res) { if(std::is_pointer<T>::value) { //THIS doesn'...

Cannot invoke method with argument list of type KeyType in Swift

I am working on custom message dispatcher in Swift. I want to have dispatcher which can: dispatch enums as events or whatever what is Hashable. Every object which implements one protocol might be added as listeners Here is the code: import Foundation protocol EventDispatcherProtocol: class { typealias T: Hashable func...

Java Generic Map with Generic Type as key/ values

I want to write a method which takes a Map as an parameter, which can contain any object as its value. I am trying to implement it using generics, but I am unable to implement it. Below is the code that I have tried so far. This code as two...

How exactly do pointers in Fortran differ from C/C++ pointers?

It might be useful to have both C/C++ programmers and Fortran programmers compare and contrast pointers in these two languages. In trying to explain to C/C++ programmers how Fortran pointers differ, I usually say pointers to functions or subroutines do not exist. I then try to make the argument that...

Why I cannot use “fgets” to read a string to an element of my Struct?

I'm trying to create a program almost like "bank" using struct, but when the program should have read the string (variable "nome" that is name in portuguese) it totally ignore the "fgets" that I used. This is the part that I was talking about : printf("\nNome: \n"); fgets(vet[cont+1].nome, sizeof(vet[cont+1].nome), stdin);...

double* android ndk crash

I'm facing a peculiar problem with the android ndk. I'm trying to read a previously stored set of bytes in an unsigned char* readBytes (previous allocated and read from file). The data needs to be interpreted as double. unsigned char* svDataOffset=(unsigned char*)(readBytes+byteCounter); unsigned char* chars=(unsigned char*)(svDataOffset+2); //offset of 2 is...