【发布时间】:2016-05-14 19:27:44
【问题描述】:
我正在尝试了解std::is_class 的实现。我复制了一些可能的实现并编译了它们,希望弄清楚它们是如何工作的。完成后,我发现所有的计算都是在编译过程中完成的(我应该早点发现,回头看),所以 gdb 不能给我更多关于到底发生了什么的细节。
我很难理解的实现是这个:
template<class T, T v>
struct integral_constant{
static constexpr T value = v;
typedef T value_type;
typedef integral_constant type;
constexpr operator value_type() const noexcept {
return value;
}
};
namespace detail {
template <class T> char test(int T::*); //this line
struct two{
char c[2];
};
template <class T> two test(...); //this line
}
//Not concerned about the is_union<T> implementation right now
template <class T>
struct is_class : std::integral_constant<bool, sizeof(detail::test<T>(0))==1
&& !std::is_union<T>::value> {};
我在使用两条注释行时遇到了问题。第一行:
template<class T> char test(int T::*);
T::* 是什么意思?另外,这不是函数声明吗?它看起来像一个,但它在没有定义函数体的情况下编译。
我要理解的第二行是:
template<class T> two test(...);
再一次,这不是没有定义主体的函数声明吗?在这种情况下,省略号是什么意思?我认为省略号作为函数参数需要在 ...? 之前定义一个参数?
我想了解这段代码在做什么。我知道我可以使用标准库中已经实现的函数,但我想了解它们是如何工作的。
参考资料:
【问题讨论】:
-
函数声明不包含正文。这是定义。
-
函数定义是函数声明,Karoly。您选择的要点是所有定义都是声明,但并非所有声明都是定义。
标签: c++ templates c++11 implementation c++-standard-library