最近正在看《C++标准库-自学教程与参考手册》(第二版),Section 5.4.1,page 122:
这种写法是没有问题的:
template <typename T> void foo (const T& val) {
if (std::is_pointer<T>::value) {
std::cout << "foo() called for a pointer" << std::endl;
} else {
std::cout << "foo() called for a value" << std::endl;
}
}
而下面这种写法却有问题,实在不理解是怎么回事?
template <typename T> void foo (const T& val) {
std::cout << (std::is_pointer<T>::value ? *val : val)
<< std::endl;
}
难道operator ?:
不是在判断完条件是否正确再对后面的表达式进行求值吗?!
You can install clang and see the compilation results of clang.
Specifically, when foo(1), the *val expression is illegal because val is of type int;
And a When foo(int*), *val is of type
int
, and val is of typeint*
. This is illegal in ?: expression, and ?: expression requires both subexpressions to be valid. Foundstd::commen_type
.PS: Regarding your question, what we actually need to do is to write a partial specialization for the pointer type instead of doing it through is_pointer.
Manual template instantiation, for int type:
Let’s look at the instantiation of int*: