简体   繁体   中英

Typedef application in c++

Is there a simple way to use a typedef based on an if condition?

example:

int depth = someObject->getDepth();

if(depth == 32){
    typedef float cast;
}
else{
     typedef double cast;
 }

 cast *data = (cast)someObject->getData();

thanks

No, you cannot do that because a typedef is a static, compile time construct. Indeed the entire type system in C++ is static. You could solve your problem with something like boost::variant<float, double> .

Refactor the implemantation in another function:

template<class T>
void foo(T* data){
  // ...
}

int depth = someObject->getDepth();
if(depth == 32)
  foo(static_cast<float*>(someObject->getData());
else
  foo(static_cast<double*>(someObject->getData());

Functions are as close as you can get

template< class cast>
void do_task(cast* object) {

}

int main() {
    int depth = someObject->getDepth();
    if (depth == 32)
        do_task( static_cast<float*>(someObject->getData()));
    else 
        do_task( static_cast<double*>(someObject->getData()));
}

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