我有以下代码:
class Foo
{
public:
int x = 4;
int & operator[](size_t index) { return x; }
};
class Bar : protected Foo
{
public:
using Foo::operator[];
Bar () { x++; }
};
int main(int agrc, char ** argv)
{
typedef int &(Bar::*getOp)(size_t index);
Bar b;
auto bVal = b[4];
getOp o = &Bar::operator[];
auto bVal2 = (b.*o)(7);
}
Run Code Online (Sandbox Code Playgroud)
但是,我不能编译它,因为
错误C2247:无法访问“ Foo”,因为“ Bar”使用“ protected”来继承“ Foo”
当我使用完using并且可以直接致电操作员后,为什么这不可能呢?有什么办法吗?
如果我将继承更改为公开,那么它将起作用。
注意:这只是较大类的一个示例。我不想使用公共继承,因为我不想这样做,Foo f = Bar()因为在中Bar,我隐藏了父方法(我没有使用virtual)。
我正在考虑在C++ 11中将char*转换为bool时强制执行类型安全性,如果你这样做,则建议你这样做
template<typename T>
void foo(T) = delete;
void foo(int f) {}
Run Code Online (Sandbox Code Playgroud)
foo只有在给出明确的int论证时,这才有效.我做了一个测试用例:
template<typename T>
void foo(T) = delete;
void foo(int f) {}
int main()
{
foo(1);
foo(3.0);
foo(short(5));
foo(float(7.0));
foo(long(9));
}
Run Code Online (Sandbox Code Playgroud)
我用coliru用g++ -std=c++14 -O2 -Wall -pedantic -pthread main.cpp && ./a.out(实例)编译代码,我得到了以下错误:
main.cpp: In function 'int main()':
main.cpp:9:12: error: use of deleted function 'void foo(T) [with T = double]'
foo(3.0);
^
main.cpp:2:6: note: declared here
void foo(T) = delete;
^
main.cpp:10:17: error: …Run Code Online (Sandbox Code Playgroud)