#include <bits/stdc++.h>
template <typename T>
struct Row {
Row() { puts("Row default"); }
Row(const Row& other) { puts("Row copy"); }
Row(Row&& other) { puts("Row move"); }
Row(T x) { puts("Row int"); }
};
int main() {
Row<Row<int>> x (10); // this works
Row<Row<int>> x2 = 10; // error
}
Run Code Online (Sandbox Code Playgroud)
为什么代码不起作用?我知道第一个执行直接初始化,第二个是复制初始化,但是当涉及到容器内的容器时,我对我来说并不容易。
编译器:clang c++20
错误信息:
没有从“int”到“Row<Row>”的可行转换
行<行> x2 = 10
我有以下代码。
#include <iostream>
struct Box {
Box() { std::cout << "constructed at " << this << '\n'; }
Box(Box const&) { puts("copy"); }
Box(Box &&) = delete;
~Box() { std::cout << "destructed at " << this << '\n'; }
};
auto f() {
Box v;
return v; // is it eligible for NVRO?
}
int main() {
auto v = f();
}
Run Code Online (Sandbox Code Playgroud)
上面的代码产生错误。 call to deleted constructor/function in both gcc and clang
但是,如果我更改代码以返回纯右值,则代码有效。
auto f() {
Box v;
return Box(); …Run Code Online (Sandbox Code Playgroud) template <typename T>
void test(const T& x) {}
int a {};
int& ref = a;
const int& c_ref = a;
test(c_ref) // T = int, x = const int&
test<int&>(ref); // T = int& , x = int&
Run Code Online (Sandbox Code Playgroud)
为什么函数模板参数 x 失去了const限定符?
#include <iostream>
struct Gadget
{
Gadget() { puts("Gadget default"); }
Gadget(char const *a) { puts("Gadget-const char* constructor"); }
Gadget(Gadget const &other) { puts("Gadget copy"); }
~Gadget() { puts("\nGadget destruction"); }
};
struct Work
{
Work() { puts("default"); }
Work(const Gadget &a) { puts("Work-Gadget constructor"); }
// Work(char const *a) { puts("Work-const char* constructor"); }
Work(Work const &other) { puts("copy"); }
~Work() { puts("\nWork destruction"); }
};
int main()
{
using namespace std;
Work w = "std"; // error here;
} …Run Code Online (Sandbox Code Playgroud) 我知道 std::greater 是如何工作的。但是,当我阅读自 C++14 以来 std::greater 的 API 时,它的默认类型为 void。因此,如果我们不将任何模板参数传递给更大的它默认为 void,如下所示。但结果是按降序排列的。
#include <iostream>
#include <set>
template< class T = void >
struct greater;
int main()
{
std::set<int, std::greater<>> s {4, 5, 6, 7}; // This transforms to std::set<int, std::greater<void>>
}
Run Code Online (Sandbox Code Playgroud)
有人可以解释这种专业化是如何运作的吗?
我有一个简单的 Box 容器,带有一个简单的实现,它需要 Car
#include <iostream>
#include <vector>
struct Car {
Car() { puts("def"); }
Car(Car const& other) { puts("copy"); }
Car& operator=(Car const& other) {
puts("assign");
return *this;
}
};
struct Box {
size_t size;
Car* ptr;
Box(size_t size)
: size(size)
, ptr{new Car[size]}
{}
Box(Box const& other)
: size{other.size}
{
ptr = new Car[size];
for (int i = 0; i < size; i++)
ptr[i] = other.ptr[i]; // hits operator=
}
};
int main() {
Box b(2);
Box b3 …Run Code Online (Sandbox Code Playgroud)