【发布时间】:2016-01-19 06:43:09
【问题描述】:
template <typename T>
struct has_xxx {
private:
using true_type = char;
using false_type = long;
template <typename C>
static true_type has_xxx_impl(decltype(&C::xxx)); // comment 1
template <typename C>
static false_type has_xxx_impl(...); // comment 2
public:
enum { value = sizeof(has_xxx_impl<T>(0)) == sizeof(true_type) }; // comment3
};
struct Foo { int xxx() {return 0;}; };
struct Foo2 {};
int main() {
static_assert(has_xxx<Foo>::value, "");
}
这是一个struct,用来检测一个struct是否有某个方法。 我对代码有一些疑问。
- 在评论 1 中,这个 '&C' 是什么意思,为什么我不能只写 'C::xxx'
- 在注释2中,参数'...'是什么意思,是参数包,还是代表任何类型的参数
- 在评论 3 中,has_xxx_impl(0) 是如何工作的? T换成Foo,那么参数0呢?为什么选择第一个函数?
【问题讨论】:
-
用 C++14 写这个非常好 :) See it live on coliru
-
@melak47 : muahaha
-
@AndyG:muahaha:p
-
@melak47:你让我到了那里 :-) 那时我们需要一些静态转换,或者使用表达式 SFINAE 来选择适当的重载。
标签: c++ c++11 c++14 template-meta-programming