【发布时间】:2015-10-11 16:30:01
【问题描述】:
您好,请考虑以下用例:
int main() {
std::shared_ptr<int> shared_ptr_to_int;
std::cout << typeid(int).name() << std::endl;
std::cout << typeid(decltype(*shared_ptr_to_int)).name() << std::endl;
if (std::is_same<decltype(*shared_ptr_to_int), int>::value) {
std::cout << "is same!\n";
}
else {
std::cout << "not the same!\n";
}
system("pause");
}
对于我的测试用例,我得到的结果“不一样”
我不确定为什么它不会导致价值为真。有人可以向我解释发生了什么吗?
PS:我的最终目标是将 shared_ptr 中存储的类型与另一种类型进行比较(在这个测试用例中,这个类型是 int)
感谢您的关注!
【问题讨论】:
-
decltype的结果是引用类型。您的实现的typeid不区分那个和非引用。 -
嗨,对于要提到使用以下内容的任何人: std::is_same<:shared_ptr>::element_type, int>::value 在我正在处理的项目中我不知道类型是 int,因此需要 decltype。 std::is_same 的第二个模板参数由模板函数调用给出,在该函数调用中它已经可以被推导和访问。