最近我见过如下例子:
#include <iostream>
class Foo {
public:
int bar;
Foo(int num): bar(num) {};
};
int main(void) {
std::cout << Foo(42).bar << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这奇怪: bar(num)意味着什么?它似乎初始化成员变量,但我以前从未见过这种语法.它看起来像一个函数/构造函数调用,但对于一个int?对我没有任何意义.也许有人可以启发我.而且,顺便说一下,还有其他类似的深奥语言功能,你永远不会在一本普通的C++书中找到它吗?
我有两个问题,即转换元类和多重继承.第一个是:为什么我会为类获取TypeError Derived而不是Derived2?
class Metaclass(type): pass
class Klass(object):
__metaclass__ = Metaclass
#class Derived(object, Klass): pass # if I uncomment this, I get a TypeError
class OtherClass(object): pass
class Derived2(OtherClass, Klass): pass # I do not get a TypeError for this
Run Code Online (Sandbox Code Playgroud)
确切的错误消息是:
TypeError: Error when calling the metaclass bases
Cannot create a consistent method resolution order (MRO) for bases object, Klass
第二个问题是:为什么super不能在这种情况下工作(如果我使用__init__的替代__new__,super再次工作):
class Metaclass(type):
def __new__(self, name, bases, dict_):
return super(Metaclass, …Run Code Online (Sandbox Code Playgroud) 以下代码会产生错误error: ‘struct Foo’ is not a valid type for a template constant parameter:
template <struct Foo>
struct Bar {
};
Run Code Online (Sandbox Code Playgroud)
为什么会这样?
template <class Foo>
struct Bar {
};
Run Code Online (Sandbox Code Playgroud)
工作得很好,甚至接受一个结构作为参数.
我正在尝试使用自定义类的瞬间作为模板参数.
class X {
public:
X() {};
};
template <class Foo, Foo foo>
struct Bar {
};
const X x;
Bar<X, x> foo;
Run Code Online (Sandbox Code Playgroud)
编译器声明x不能出现在常量表达式中.为什么?在编译时构造该对象有一切.