小编Mar*_*hrs的帖子

为什么std :: in_place_t的构造函数默认且显式?

cppreference显示以下定义std::in_place_t

struct in_place_t {
    explicit in_place_t() = default;
};
inline constexpr std::in_place_t in_place{};
Run Code Online (Sandbox Code Playgroud)

他们为什么要添加一个explicit默认的构造函数?为什么不排除它?有什么好处?

c++ explicit std explicit-constructor defaulted-functions

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

复制返回值和noexcept的省略

我有一个这样的功能模板:

template <typename T>
constexpr auto myfunc() noexcept
{
    return T{};
}
Run Code Online (Sandbox Code Playgroud)

由于复制省略,此功能模板是否保证是noexcept?如果在构造函数中抛出异常,这是在函数内部还是外部发生?

c++ optimization exception noexcept

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

按值传递参数时异常在哪里抛出

复制时我有一个类型抛出:

struct A { A(const A&) { throw 1; } };

void doit(A)
{
}

int main()
{
    A a;
    doit(a);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

异常是在函数内部还是外部抛出?我可以将该函数声明为 noexcept 吗?

c++ exception pass-by-value language-lawyer noexcept

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

为什么 consteval 函数内的模板接受函数参数作为其模板参数之一?

我尝试从我的代码库中提取一个最小的工作示例:

#include <concepts>

enum class unit_type
{
};

template <typename Candidate>
concept unit_c = requires()
{
    requires std::semiregular<Candidate>;
    { Candidate::type } -> std::same_as<const unit_type&>;
};

struct unit
{
    static constexpr unit_type type{};
};

template<unit_c auto unit_1, unit_c auto unit_2>
struct unit_product
{
    static constexpr unit_type type{};
};

template <unit_c Unit1, unit_c Unit2>
consteval unit_c auto operator*(Unit1 unit_1, Unit2 unit_2) noexcept
{
    return unit_product<unit_1, unit_2>{};
}

int main()
{
    constexpr unit_c auto a = unit{} * unit{};

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

上面的代码编译得很好。但为什么?我认为不能将 …

c++ templates c++20 consteval

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

右值参考或转发参考?

我知道以下功能

template <typename T>
void do_something(T&& arg);
Run Code Online (Sandbox Code Playgroud)

function参数是转发引用.但在以下情况下它仍然是转发引用或右值引用?

template <typename T>
class MyClass
{
    void do_something(T&& arg);
};
Run Code Online (Sandbox Code Playgroud)

我认为它仍然是转发参考,但我不确定.此外,我想知道,如果结果不是我想要的,可以采取什么措施来强制执行右值引用或转发引用.

c++

4
推荐指数
2
解决办法
301
查看次数

require 表达式的隐式可复制要求

以下代码是否需要 T 的隐式复制构造函数,因为参数是按值传递的?或者它的行为类似于 decltype 并且不涉及真正的构造?

template<typename T>
concept Addable = requires (T a, T b){ a + b; };
Run Code Online (Sandbox Code Playgroud)

c++ c++-concepts c++20 requires-expression

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