简体   繁体   中英

How do i pass a type name to a function?

My problem is that i can't pass a type name to a function. I don't really know how to do it, so i ask myself if that's even possible, but i guess so.

So i want to create a function which accepts type names like sizeof() does.

sizeof(int); // accepts a type name not a var

My code for trying to realize this looks like this:

#include "stdafx.h"
using namespace std;

void foo( WHAT TO PUT HERE? ) {...};
int main(){
    foo(float);
    return EXIT_SUCCES;
}

Basically my problem is that i don't know how to make the function foo accepting type names like sizeof(), What to put in the declaration to make it accepting type names?

Thank your for reading and helping me.

First of all sizeof is not a function, but an operator (processed only during compilation), and you can't create own operators.

What you probably need is "meta-function" - template.

template <typename T>
void foo() { ... /* Use T as type, ex. sizeof(T) */ ... }

and call it: foo<MyType>()

do remember - all template parameters etc are resolved at compile time, there's no way to pass type at runtime in C++ (at least any type)

Return type can be either specified as template parameter ( T foo() ), derived from T ( typename T::return_type foo() ) - if you prepare T properly, or you can provide template specialization for types you need ( template <> float foo<int>() to return floats for foo<int> calls)

If you really need you can then create macro to hide template #define fooCall(X) foo<X>() . But please - do not do it , code should clearly state what it does and when it does it. Difference between <> and () show to readers, when code is evaluated at runtime and when on compile time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM