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默认的构造函数?为什么不排除它?有什么好处?
我有一个这样的功能模板:
template <typename T>
constexpr auto myfunc() noexcept
{
return T{};
}
Run Code Online (Sandbox Code Playgroud)
由于复制省略,此功能模板是否保证是noexcept?如果在构造函数中抛出异常,这是在函数内部还是外部发生?
复制时我有一个类型抛出:
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 吗?
我尝试从我的代码库中提取一个最小的工作示例:
#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)
上面的代码编译得很好。但为什么?我认为不能将 …
我知道以下功能
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)
我认为它仍然是转发参考,但我不确定.此外,我想知道,如果结果不是我想要的,可以采取什么措施来强制执行右值引用或转发引用.
以下代码是否需要 T 的隐式复制构造函数,因为参数是按值传递的?或者它的行为类似于 decltype 并且不涉及真正的构造?
template<typename T>
concept Addable = requires (T a, T b){ a + b; };
Run Code Online (Sandbox Code Playgroud) c++ ×6
c++20 ×2
exception ×2
noexcept ×2
c++-concepts ×1
consteval ×1
explicit ×1
optimization ×1
std ×1
templates ×1