小编Jak*_*idt的帖子

为什么我不需要在 C++20 中的依赖类型之前指定“typename”?

这段代码在 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)

代码游乐场

c++ templates typename language-lawyer c++20

70
推荐指数
2
解决办法
3656
查看次数

为什么 bool(val) 比 val.operator bool() 更喜欢双重隐式转换?

下面的一段代码取消引用 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)
  1. 为什么bool(f)调用bool(f.operator int&())而不是f.operator bool()预期的那样?
  2. 有没有办法在标记为的情况下按预期bool(f)拨打电话?f.operator bool()operator int&explicit

c++ operator-overloading type-conversion language-lawyer implicit-conversion

7
推荐指数
1
解决办法
92
查看次数

从一个新的位置访问一个静态 constexpr 成员是一个常量表达式吗?

澄清一下,以下程序格式是否正确?

#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)

gccmsvc接受,但clang因错误而拒绝 read of non-constexpr variable 'p' is not allowed in a constant expression,谁是对的?

c++ static-members placement-new language-lawyer constant-expression

6
推荐指数
1
解决办法
82
查看次数

在调用析构函数之前是否有任何实际理由来检查某物是否可破坏?

所以我一直在尝试实现一个变体/标记的联合类,并且需要一种方法来编写通用析构函数并犯了我认为是一个愚蠢的错误,忘记了某些类型没有析构函数,做类似的事情

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)

但是代码之间实际上有什么区别吗?第一个感觉非常不确定的行为/对我来说是错误的。

c++

4
推荐指数
1
解决办法
98
查看次数

为什么 char 可以在 std::array 中初始化为 nullptr,但不能单独初始化?

此代码无法编译(使用 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)


为什么会有区别?

c++

1
推荐指数
1
解决办法
71
查看次数