C++ boost enable_if问题
我有什么办法可以简化以下陈述吗? (可能使用boost::enable_if
)。
我有一个简单的类结构 - Base
基类、Derived1
、Derived2
继承自 Base
。
我有以下代码:
template <typename Y> struct translator_between<Base, Y> {
typedef some_translator<Base, Y> type;
};
template <typename Y> struct translator_between<Derived1, Y> {
typedef some_translator<Derived1, Y> type;
};
template <typename Y> struct translator_between<Derived2, Y> {
typedef some_translator<Derived2, Y> type;
};
我想使用 translator_ Between
的一个模板特化来编写相同的语句。
我希望能够编写的示例(伪代码):
template <typename Class, typename Y>
ONLY_INSTANTIATE_THIS_TEMPLATE_IF (Class is 'Base' or any derived from 'Base')
struct translator_between<Class, Y> {
typedef some_translator<Class, Y> type;
};
使用 boost::enable_if
和 boost::is_base_of
实现此目的的任何方法>?
Do I have any way to simplify the following statements? (probably, using boost::enable_if
).
I have a simple class structure - Base
base class, Derived1
, Derived2
inherit from Base
.
I have the following code:
template <typename Y> struct translator_between<Base, Y> {
typedef some_translator<Base, Y> type;
};
template <typename Y> struct translator_between<Derived1, Y> {
typedef some_translator<Derived1, Y> type;
};
template <typename Y> struct translator_between<Derived2, Y> {
typedef some_translator<Derived2, Y> type;
};
I want to write the same statement using one template specialization of translator_between
.
An example (pseudocode) of what I want to be able to write:
template <typename Class, typename Y>
ONLY_INSTANTIATE_THIS_TEMPLATE_IF (Class is 'Base' or any derived from 'Base')
struct translator_between<Class, Y> {
typedef some_translator<Class, Y> type;
};
Any way to achieve this using boost::enable_if
and boost::is_base_of
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
首先,您必须在以下选项中进行选择:
is_base_of
is_convertible
两者都可以在
中找到,后者更加宽容。如果您只是想阻止某种组合的此类实例化,请使用静态断言:
由于此处没有发生重载决策,因此您不需要
enable_if
。First, you'll have to pick your choice among:
is_base_of
is_convertible
both can be found in
<boost/type_traits.hpp>
, the latter being more permissive.If you with to simply prevent the instantiation of this type for some combination, then use a static assert:
Since there is no overload resolution taking place here, you don't need
enable_if
.我不认为 boost::enable_if 有帮助,因为 SFINAE 似乎更倾向于在函数重载之间进行选择。
您当然可以使用带有
bool
参数的模板来优化选择:I don''t think
boost::enable_if
helps, because SFINAE seems to be rather about selecting between function overloads.You can of course use templates with
bool
parameters to refine the choice:您可以在此处使用 anable_if 和此宏来使其更具可读性:
然后您可以像这样定义您的类:
You can use anable_if and this macro here to make it more readable:
Then you can define your class like this: