使用sfinae来测试命名空间成员存在 [英] use sfinae to test namespace members existence

查看:129
本文介绍了使用sfinae来测试命名空间成员存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出是否可以使用sfinae测试命名空间成员存在。
Google对此不屑一顾。我试过下面的代码,但它失败。

I was trying to figure out if it is possible to use sfinae to test namespace member existence. Google is rather silent about it. I've tried the following code, but it fails.

namespace xyz{
 struct abc{};
}

struct abc{};

struct test_xyz{ 
 typedef char yes;
 typedef struct{ char a[2]; } no;

 template <class C> static yes test(xyz::C = xyz::C()); //lets assume it has default constructor
 template <class C> static no test(...);

 const bool has_abc = sizeof(test_xyz::test<abc>()) == sizeof(yes);
};

有什么想法吗?

推荐答案

不,这不会工作。也没有办法以这样的方式使用SFINAE(这是最后一次讨论在usenet上对一些C ++ 0x组件的兼容性测试)。 xyz :: C 中的C与模板参数完全无关。

No, that won't work. There is also no way to use SFINAE in such a way (this was last discussed on usenet for a compatibility test against some C++0x component). The C inside xyz::C is not related to the template parameter at all.

请记住,模板不仅仅是宏。参数 C 不仅表示一段文本,还表示语义实体。在这种情况下,它是一种类型。它已经绑定到它作为一个参数的意义。也就是说,如果你的类有一个名为 abc 的成员,参数的含义仍然不会改变。

Remember that templates are not just macros. The parameter C denotes not just a piece of text, but a semantical entity. In this case it is a type. It's bound already to the meaning it has as an argument. That is, if your class had a member of name abc, the meaning of the parameter still would not change.

如果你想要的是使用一些struct xyz :: abc c> others :: abc 否则,你可以做一些技巧来到那里,但我不知道一个方法,它没有触摸 xyz

If all you want is to use some struct xyz::abc if it exists, and others::abc otherwise, you can do some tricks to get there, but I'm not aware of a way that does it without touching xyz

namespace others {
  struct abc{};
}

namespace fallbacks {
  using others::abc;
}

namespace xyz {
  using namespace fallbacks;
}



现在如果你说 xyz :: abc xyz 包含一个声明的成员,它将引用该成员(该成员将隐藏 fallbacks 。但是如果它不包含那个成员,那么将会找到using指令的名称并引用 fallbacks :: abc

Now if you say xyz::abc and xyz contains a member declared so, it will refer to that member (that member will hide the one in fallbacks. However if it doesn't contain that member, then the using directive's name will be found and refer to fallbacks::abc.

这篇关于使用sfinae来测试命名空间成员存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆