是否可以判断一个方法在编译时是否可以公开访问
Is it possible to tell if a method is publicly accessible at compile-time
在C++中,如果类具有命名字段、typedef或方法,则在编译时需要使用SFINAE技巧。
我的问题是:我们是否也可以以某种方式查询一个方法是否可以访问?比如区分私人和公共方法。
例如,如果我有一个像class T : private std::vector<int> { ... };
一样从std::vector
私有继承的类,我不想检测它的begin
方法,因为它是不可公开访问的。
当搜索around时,我只得到检测方法的代码,而不是可见性。。。我得到的最接近的是这个,它解决了继承的方法,但不清楚它是如何与可见性交互的。很明显,我可以测试,但我关心编译器特定的行为,因为我正在做一个关于旧微软编译器的项目:\
编辑/澄清:这里说C++标准改变了它对这个问题的看法:在C++03中,任何可见或不可见的成员都是可替代的,但由于C++11,只有可见的成员是可替换的。这是正确的吗?
我用下面的代码做了一些测试,它检测value_type
typedef。我不确定标准是怎么说的,但我用不同的编译器进行了编译,结果如下:
- gcc:4.4
true
|4.5true
|4.6true
|4.7true
|4.8false
|4.9false
之前 - Clang:3.3
fail
- icc:13
true
- msvc:2005
true
|2010true
|2012true
这是代码:
#include <vector>
typedef char yes;
typedef int no;
template<class T> struct has_value_type {
template<class U> static yes test(typename U::value_type*);
template<class U> static no test(...);
static const bool value = sizeof(test<T>(0)) == sizeof(yes);
};
class C : private std::vector<int> { };
int main() {
return has_value_type<C>::value;
}
如您发现的示例注释所述:
"建议的SFINAE仅在方法是公共的情况下有效">
因此,它将只检测应该解决您的问题的公共方法。
相关文章:
- 是否可以在编译时初始化数组,以便在运行时不会花费时间?
- 关于std::move的使用,是否有编译警告
- 标准是否严格定义了该程序应该如何编译?
- 是否可以在编译时限制类的实例数?
- 检查编译时是否存在静态函数
- 是否可以编译 Gtk+ 应用程序以同时在 Gtk 2 和 3 上运行
- std::less是否应该允许在编译时比较不相关的指针?
- 编译时检查特征专用化是否具有唯一 ID
- GTK C++:找不到信号处理程序 您是否使用 -rdynamic 进行了编译?
- 是否可以在编译时初始化对象的 C 样式函数指针,以便它调用对象的成员函数?
- 如何确定integer_sequence在编译时是否包含给定的数字?
- 知道模板参数在编译时是否为 const char*?
- 全局变量在 C++ 中是否显着提高了编译速度?
- 检查该类在编译时C++中是否有任何基类
- 如何判断是否在编译时计算了"constexpr"(无需手动检查)
- cMake/cTest:检查代码是否编译
- 我怎么知道编译器是否C++编译时计算表达式
- 在线编译器工具是否执行所有操作,或者它们只是检查是否编译
- constexpr数组成员是否编译时间常量
- 检查表达式是否编译的可移植方法