# How can I create a function taking a type as an argument (like sizeof(type) or PyMem_New(Type,Size))

This topic is 2518 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hi,

I wonder if it is possible to create a function that takes a type (f. ex. float, some class etc) as an argument. just like sizeof() does (I know it is an operator, but Python function c API PyMem_New does something like that too)

the simpliest (and quite dumb) example of it working would be:
 size_t f(type) { return sizeof(type); } 

of course i need it for something different.

Misery

##### Share on other sites
What language? And it would be nice if you told us what you are trying to accomplish too.

##### Share on other sites
C++ language,
Of course, sorry for writing too short post

I am trying to make a class that in default case will just use standard new and delete operator. But when necessary it will use an overriden operator using memory pool or a function allocating the memory. I am willing to wrap that class also for python, and therefore I need a function pointer to:
 type PyMem_New(type,size)

##### Share on other sites
In C++ you can use templates to achieve what you want, although the syntax would look more like PyMem_New<type>(size)' or even just PyMem_New<type>()', since the size can be deduced from the type. Template specialization would allow you to change the default behavior for certain types.

I don't think you'll be able to wrap it for Python, though.

##### Share on other sites
I've heard that using SWIG and C++ linker should allow to do that wrapping quite painless. We'll see.
Anyways Your idea seems quite nice for solving my problem at the moment. Thanks a lot.

1. 1
2. 2
Rutin
20
3. 3
khawk
17
4. 4
A4L
14
5. 5

• 12
• 16
• 26
• 10
• 44
• ### Forum Statistics

• Total Topics
633759
• Total Posts
3013720
×