简体   繁体   English

C ++编译时类型比较

[英]C++ compile-time type comparsion

Consider the function foo . 考虑函数foo

template <typename T>
void foo() {
    do_something();
    if (T == int) {
        do_somehting_else();
    }
}

In other words, I want it to do_something() and then, if the type is int , do_something_else() 换句话说,我想要它do_something()然后,如果类型是intdo_something_else()

Of course if (T == int) { won't compile. 当然if (T == int) {将无法编译。 Still: is there any way to compare types in compile-time in C++? 仍然:有没有办法在C ++中比较编译时的类型?

You can use 您可以使用

#include <type_traits>

// ...

template <typename T>
void foo() {
    do_something();
    if (std::is_same<T,int>::value) {
        do_somehting_else();
    }
}

You can learn more about type traits here . 您可以在此处了解有关类型特征的更多信息。

Just use a template specialization. 只需使用模板专业化。

template <typename T> void foo() { do_something(); }

template<> void foo<int>() { do_something(); do_something_else(); };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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