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

Started by
3 comments, last by Misery 12 years, 2 months ago
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.

Thanks in advance and regards
Misery
Advertisement
What language? And it would be nice if you told us what you are trying to accomplish too.
C++ language,
Of course, sorry for writing too short post unsure.png

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)

thanks for an answer
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.
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.

This topic is closed to new replies.

Advertisement