这段代码在 C++20(使用 gcc 10.1)中编译,typename在依赖类型之前没有使用关键字std::vector<T>::iterator。为什么要编译?
#include <vector>
template<typename T>
std::vector<T>::iterator // Why does this not require "typename" before it?
f() { return {}; }
int main() {
auto fptr = &f<int>;
}
Run Code Online (Sandbox Code Playgroud)
下面的一段代码取消引用 a nullptr。
struct Foo {
int *bar;
operator int&() {
return *bar;
}
explicit operator bool() const {
return bar;
}
};
int main() {
Foo f {nullptr};
auto _ = bool(f);
}
Run Code Online (Sandbox Code Playgroud)
bool(f)调用bool(f.operator int&())而不是f.operator bool()预期的那样?bool(f)拨打电话?f.operator bool()operator int&explicitc++ operator-overloading type-conversion language-lawyer implicit-conversion
澄清一下,以下程序格式是否正确?
#include <new>
char foo[32];
struct bar {
static constexpr int foobar = 42;
};
int main()
{
auto p = new (foo) bar();
static_assert(p->foobar == 42);
}
Run Code Online (Sandbox Code Playgroud)
gcc和msvc接受,但clang因错误而拒绝
read of non-constexpr variable 'p' is not allowed in a constant expression,谁是对的?
c++ static-members placement-new language-lawyer constant-expression
所以我一直在尝试实现一个变体/标记的联合类,并且需要一种方法来编写通用析构函数并犯了我认为是一个愚蠢的错误,忘记了某些类型没有析构函数,做类似的事情
template<typename T>
void destruct(T& thing) {
thing.~T();
}
Run Code Online (Sandbox Code Playgroud)
然而,即使对于没有析构函数的类型,如int或,这也能正常工作struct A {int b;};。我仍然认为使用这样的东西更具可读性和更容易推理
template<typename T>
void destruct(T& thing) {
if constexpr(std::is_destructible<T>::value) {
thing.~T();
}
}
Run Code Online (Sandbox Code Playgroud)
但是代码之间实际上有什么区别吗?第一个感觉非常不确定的行为/对我来说是错误的。
此代码无法编译(使用 gcc 9.3)...
int main() {
char bar = nullptr; //error: cannot convert ‘std::nullptr_t’ to ‘char’ in initialization
}
Run Code Online (Sandbox Code Playgroud)
但是这段代码确实可以编译...
#include <array>
int main() {
std::array<char, 1> foo = {nullptr}; // foo[0] == char(0), why?
}
Run Code Online (Sandbox Code Playgroud)
为什么会有区别?