如何检查函数的模板参数是否具有某种类型?

Nar*_*rek 9 c++ templates typechecking

说我有模板类型的函数Ť和其它两个类.

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

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

Ker*_* SB 9

如果你真的只想要一个布尔来测试是否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;
Run Code Online (Sandbox Code Playgroud)

你可以自己写一下这个小班:

template <typename, typename> struct is_same { static const bool value = false;};
template <typename T> struct is_same<T,T> { static const bool value = true;};
Run Code Online (Sandbox Code Playgroud)

通常,虽然你可能会发现更方便地收拾你的分支代码到你专门用于单独的类或函数AB,因为这会给你一个编译时的条件.相比之下,检查if (T_is_A)只能在运行时完成.


jpa*_*cek 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>();
}
Run Code Online (Sandbox Code Playgroud)