在gnu c ++中有__if_exists的等价物吗? [英] Is there an equivalent for __if_exists in gnu c++?
问题描述
__ if_exists是用于在编译时测试标识符存在的微软特定关键字:
__if_exists is a microsoft specific keyword for testing existence of identifiers at compile time:
在faked模板专门化中,它可能非常方便,因为在某些情况下,比其他方法,如真正的专门化或重载或其他方法,真的更简单,可读性更好的方式。
It can come in very handy at "faked" template specialization as in some cases it provides a really much more simple, readable and better performing way than other methods like "real" specialization or overloading or whatever.
但现在我必须移植一个大项目到gnu c我想我会开始一点哭泣,如果我必须找到其他方式(当然很少)的场合,我使用它
But now I have to port a big project to gnu c++ and I think I would start a little bit of crying if I would have to find other ways for the (admittedly few) occasions I used it
推荐答案
这是一个crappy关键字在我看来...
That's a crappy keyword in my opinion...
不幸的是,它不存在于gcc就我所知,但然后我可能根本不了解它。
Unfortunately, it doesn't exist in gcc as far as I know, but then I may simply not know about it.
正确的C ++方式来处理这个问题是通过使用概念,即根据一些要求调整类型上的操作。
The proper C++ way to handle this is through the use of Concepts, ie adapt the operations carried on the type depending on some requirements.
通常,它使用 traits
而不是真正的概念来执行,因为它更容易放置:
Usually, it's carried out with traits
rather than real concepts, because it's easier to put in place:
template <typename T>
struct has_dump: boost::mpl::false_ {};
然后通过专门化 has_dump
结构。
最简单的是定义3个方法,一个路由,另外两个执行不同的分支:
The simplest is to define 3 methods, one to route, the two others to execute the different branches:
template <typename T>
void dump(T& t, boost::mpl::true_ const& dummy)
{
t.Dump();
}
template <typename T>
void dump(T& t, boost::mpl::false_ const& dummy)
{
std::cout << typeid(T).name() << " does not have Dump\n";
}
template <typename T>
void dump(T& t) { dump(t, has_dump<T>()); }
类型traits的另一个使用将与 enable_if
设施:
Another use of the type traits would be in conjunction with the enable_if
facilities:
template <typename T>
typename boost::enable_if< has_dump<T> >::type dump(T& t)
{
t.Dump();
}
// disable_if exists too...
这里,如果类型没有启用 has_dump
,而不是运行时错误消息,您可能会收到编译时错误。
Here, instead of a runtime error message, you can get a compile-time error if the type does not have has_dump
enabled, not sure if that's you want.
然而,这两种方法都相当麻烦,因为检测不是自动的。这就是为什么有Boost.Concept库。
However both those methods are quite cumbersome, since the detection isn't automated. That is why there is the Boost.Concept library.
这个想法是,检查将由一个Concept对象执行,被创建来测试需求,因此你不再需要专门化特性,这使得开发更容易。然而,我总是发现Boost.Concept的文档有点欠缺。
The idea is that the check will be performed by a Concept object, created to test the requirements, and thus you don't have to specialize traits any longer, which make easier on the development. However I have always found the documentation of Boost.Concept to be somewhat lacking.
这篇关于在gnu c ++中有__if_exists的等价物吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!