先上代码
#include <iostream>
using namespace std;
template <bool flag, typename T, typename U>
struct Select
{
typedef T Result;
};
template <typename T, typename U>
struct Select<false, T, U>
{
typedef U Result;
};
template<class T>
void f(T*)
{
cout << "pointer version.\n";
}
template<class T>
void f(T)
{
cout << "non-pointer version.\n";
}
int main(int argc, char* argv[])
{
int i = 0;
f(Select<true, double, double*>::Result(i));
f(Select<false, double, double*>::Result(i));
return 0;
}
上述代码运行结果:
non-pointer version.
pointer version.
应用
例如, 我们用vector来存储数值, 对于有多态属性的类, 我们需要指针存储, 非多态用值存储. 用上述方式就可以在编译时自动判断, 生成对应的代码.