将类型解析为 class::typedef 的更短方法
我有几节课。目前它们由一个符号分隔。其中很少包含 type
(typedef
),也很少有不包含它。
struct A { ... public: typedef someclass type; }
struct B { ... };
我想以这样的方式实现 SFINAE 类,
Resolve<A>::type o1; // should resolve to 'A::type'
Resolve<B>::type o2; // should resolve to 'B'
一种方法是使用基本的 SFINAE,如下所示上一个链接检查 T
是否包含 type
,然后使用 bool
检查器。例如,
template <typename T>
struct has_type {
typedef char yes[3];
template <typename C> static yes& test(typename C::type*);
template <typename> static char& test(...);
static const bool value = sizeof(test<T>(0)) == sizeof(yes);
};
template<typename TYPE, bool = has_type<TYPE>::value>
struct Contains { typedef typename TYPE::type type; };
template<typename TYPE>
struct Contains<TYPE, false> { typedef TYPE type; };
template<class TYPE>
struct Resolve {
typedef typename Contains<TYPE>::type type;
};
演示。
问题:我的代码中有很多这样的实例,我觉得这种方法可能会大大增加编译时间。因为必须经历两次迭代:第一次是查找 type
,第二次是通过解析 bool
标志。
有没有更快的方法来实现减少编译时间?
[旁注:在这种情况下,我将 type
作为 A
和 B
之间的分隔符。但是,我可以自由地将任何内容放入 A
中,以将其与 B
分开。也欢迎与此相关的想法。]
I have several classes. For now they are separated by one symbol. Few of them contains type
(a typedef
) and few of them doesn't have it.
struct A { ... public: typedef someclass type; }
struct B { ... };
I want to implement a SFINAE class in such a way that,
Resolve<A>::type o1; // should resolve to 'A::type'
Resolve<B>::type o2; // should resolve to 'B'
One way is to use basic SFINAE as shown in previous link which checks if the T
contains a type
and then use a bool
checker. For example,
template <typename T>
struct has_type {
typedef char yes[3];
template <typename C> static yes& test(typename C::type*);
template <typename> static char& test(...);
static const bool value = sizeof(test<T>(0)) == sizeof(yes);
};
template<typename TYPE, bool = has_type<TYPE>::value>
struct Contains { typedef typename TYPE::type type; };
template<typename TYPE>
struct Contains<TYPE, false> { typedef TYPE type; };
template<class TYPE>
struct Resolve {
typedef typename Contains<TYPE>::type type;
};
Demo.
Question: I have many such instances through out the code and I feel that this method may increase compile-time considerably. Because one has to go through two iterations: 1st for finding type
and 2nd through resolving bool
flag.
Is there a faster way to achieve to reduce the compile time ?
[Side Note: In this case, I have put type
as separator between A
and B
. However, I am free to put anything inside A
which will separate it from B
. Ideas related to that are also welcome.]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)