Kim*_*-wu 3 c++ templates stl type-traits
我正在观看最新的C9讲座并注意到一些有趣的东西......
在他对type_traits的介绍中,Stephan使用了以下(正如他所说的,做作的)示例:
template <typename T> void foo(T t, true_type)
{
std::cout << t << " is integral";
}
template <typename T> void foo(T t, false_type)
{
std::cout << t << " is not integral";
}
template <typename T> void bar(T t)
{
foo(t, typename is_integral<T>::type());
}
这看起来要复杂得多:
template <typename T> void foo(T t)
{
if(std::is_integral<T>::value)
std::cout << "integral";
else
std::cout << "not integral";
}
这样做的方法有问题吗?他的方式更好吗?为什么?
谢谢.
下面的例子应该说明不同之处.让我们添加struct X:
struct X
{
X(int)
{
}
};
Run Code Online (Sandbox Code Playgroud)
并修改一个foo如下:
template <typename T> void foo(T t, true_type)
{
std::cout << t << " is integral";
X x(t);
}
template <typename T> void foo(T t, false_type)
{
std::cout << t << " is not integral";
}
Run Code Online (Sandbox Code Playgroud)
然后:
template <typename T> void bar(T t)
{
foo(t, typename is_integral<T>::type());
}
Run Code Online (Sandbox Code Playgroud)
仍然会为所有T类型编译(包括整数类型;它可能会导致警告,但会编译).
其他等效代码:
template <typename T> void foo(T t)
{
if(std::is_integral<T>::value)
{
std::cout << "integral";
X x(t);
}
else
std::cout << "not integral";
}
Run Code Online (Sandbox Code Playgroud)
往往不能编译,你将不能够实例化X的类型具有操作INT()等则积分,最终的浮点和用户定义的类(操作员短()或运营长()不会做).