我不明白为什么以下不能编译(例如在 gcc 9.10 或 MS VS C++ 2019 中):
class X {
public:
friend bool operator==(int, X const &);
};
int main() {
2 == X(); // ok...
static_cast<bool (*)(int, X const &)>(&operator==); // Error: 'operator==' not defined
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但以下代码编译没有任何问题:
class X {
public:
};
bool operator==(int, X const &);
int main() {
2 == X(); // ok...
static_cast<bool (*)(int, X const &)>(&operator==); // OK!
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我的期望是 X 的友元函数 (operator==) 表现为独立函数 (operator==)。我缺少什么?谢谢
我知道指针算法不允许用于空指针。但想象一下我有这样的事情:
class MyArray {
int *arrayBegin; // pointer to the first array item, NULL for an empty array
unsigned arraySize; // size of the array, zero for an empty array
public:
int *begin() const { return arrayBegin; }
int *end() const { return arrayBegin + arraySize; } // possible? (arrayBegin may be null)
Run Code Online (Sandbox Code Playgroud)
是否有可能(允许)进行上述end()实现?或者是否有必要拥有:
int *end() const { return (arraySize == 0) ? nullptr : (arrayBegin + arraySize); }
Run Code Online (Sandbox Code Playgroud)
避免使用 nullptr 进行指针运算,因为arrayBegin空数组为 null(尽管arraySize在这种情况下也为零)?
我知道可以存储 …
我刚刚发现可以在for语句的第二个"参数"中放置一个声明.但是我无法找到它在该参数中声明的对象的构造/销毁方面的行为方式.
我们有这个简单的代码:
struct C {
C() { puts("constr"); }
~C() { puts("destr"); }
};
int main() {
for (int i = 0; auto h = std::make_unique<C>(); i++) {
puts("in");
}
}
Run Code Online (Sandbox Code Playgroud)
请你告诉我什么时候h被销毁?(之后puts("in"),i++......?).它是如何与表现break;和continue;?
谢谢你的澄清!
如果我有例如:
template <class T>
class MyOptional { /*...*/ };
Run Code Online (Sandbox Code Playgroud)
我知道我可以定义一个专门化,例如T = bool,它将具有不同的(单独的)实现:
template <> class MyOptional<bool> { /*...*/ };
Run Code Online (Sandbox Code Playgroud)
但是有可能说这种T=bool专业化等于另一种类型(例如MyOptBool)吗?像这样的东西:
class MyOptBool { /*...*/ };
using Optional<bool> = MyOptBool; /* impossible but looking for similar functionality */
Run Code Online (Sandbox Code Playgroud)
我发现的唯一想法是使用继承:
class MyOptBool { /*...*/ };
template <> class MyOptional<bool> : public MyOptBool {
using MyOptBool::MyOptBool;
};
Run Code Online (Sandbox Code Playgroud)
第一个问题:还有更优雅的解决方案吗?(仅仅是为了好奇+我有一些转换问题,等等).
第二个问题: "变通方法"是否使用继承来声明两个常用的类(在一些重要的库中等)?
我一定错过了C ++规范中的某些内容,因为我无法解释为什么以下代码成功编译:
class MyClass { static void fun(); };
int main() { MyClass::MyClass::MyClass::fun(); }
Run Code Online (Sandbox Code Playgroud)
有人可以指出我的标准还是要向我解释语义?我猜想只MyClass::允许一个。两个MyClass::MyClass::应该引起错误。我尝试使用MS Visual C ++ 2017和GNU C ++ 6.2.0进行了计数MyClass::。
这不仅是一个理论问题。我想在存在子类的情况下使用SFINAE和条件编译。在基类的名称与子类的名称相同之前,效果良好:
template <class T> void callWorkout() { T::SubClass::workout(); }
struct X { struct SubClass { static void workout(); }; };
struct Y { /*empty*/ };
struct SubClass { static void workout(); };
int main() {
callWorkout<X>(); // works fine - compiled
callWorkout<Y>(); // works "fine" - not compiled, no SubClass in Y …Run Code Online (Sandbox Code Playgroud)