9

假设我有一个模板类型为T和另外两个类AB的函数。

template <typename T>
void func(const T & t)
{
    ...........
    //check if T == A do something
    ...........
    //check if T == B do some other thing
}

如何进行这两项检查(不使用 Boost 库)?

4

3 回答 3

10

如果您实际上只是想要一个布尔值来测试是否T == A,那么您可以使用is_same, 在 C++11 中作为std::is_same, 或在 TR1 之前作为std::tr1::is_same:

const bool T_is_A = std::is_same<T, A>::value;

您可以自己编写这个小类:

template <typename, typename> struct is_same { static const bool value = false;};
template <typename T> struct is_same<T,T> { static const bool value = true;};

通常,尽管您可能会发现将分支代码打包到您专门用于的单独的类或函数中更方便AB因为这将为您提供编译时条件。相比之下,检查if (T_is_A)只能在运行时进行。

于 2011-10-04T12:49:51.217 回答
7

创建具有专业化的功能模板,这将做你想做的事情。

template <class T>
void doSomething() {}

template <>
void doSomething<A>() { /* actual code */ }

template <class T>
void doSomeOtherThing() {}

template <>
void doSomeOtherThing<B>() { /* actual code */ }

template <typename T>
void func(const T & t)
{
    ...........
    //check if T == A do something
    doSomething<T>();
    ...........
    //check if T == B do some other thing
    doSomeOtherThing<T>();
}
于 2011-10-04T12:38:58.707 回答
3

如果您想func对某些参数类型进行特殊实现,只需为该类型创建一个特定的重载:

template <typename T>
void func(const T & t) {
   // generic code
}

void func(const A & t) {
   // code for A
}
于 2011-10-04T12:38:37.677 回答