我正在尝试制作模板包装函数,该函数应该转发参数并返回值。我无法决定使用什么auto&&或decltype(auto)返回类型更好。我读过 Scott Meyers 的文章,并理解与不剥离 ref_qualifiersdecltype(auto)相比,有必要返回。auto据我了解,同样的论点适用于使用auto&&over auto。现在我有以下问题:
decltype(auto)和何时没有区别?auto&&rvalue,例如:return int{};?返回值会是悬空引用吗?decltype(auto)和 和有什么区别auto&&?什么更适合作为远期回报类型?我有以下代码:
#include <iostream>
struct T {
int a;
T() = default;
T(T& other) {
std::cout << "copy &\n";
}
T(T&& other) {
std::cout << "move &&\n";
}
};
void foo(T&& x) {
T y(x); // why is copy ctor called??????
}
int main() {
T x;
foo(std::move(x));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
foo()我不明白为什么即使接受右值引用,复制构造函数也优于移动构造函数。
我有一个模板类,想知道当模板类变量用作函数的模板参数时如何获取模板类变量类型。我尝试执行以下操作
#include <iostream>
#include <type_traits>
using namespace std;
template <typename T>
class foo
{
};
template <typename templateClass>
void f()
{
if (is_same<typename templateClass::T, int>::value)
cout << "int";
else if (is_same<typename templateClass::T, double>::value)
cout << "double";
else
cout << "Unknown type";
}
int main()
{
f<foo<double>>();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
该代码无法编译,因为no type named 'T' in 'foo<double>'. 然后我稍微改变了一下:
#include <iostream>
#include <type_traits>
using namespace std;
template <typename T>
class foo
{
public:
using Type = T; //can't write : using …Run Code Online (Sandbox Code Playgroud) 最近阅读一些代码时,我遇到了几个包含
#pragma once在文件开头的 .cpp 文件。我知道它通常在 .h 文件中用作防护。
在什么情况下#pragma once应该/可以/必须在 .cpp 文件中使用?
我见过std::mt19937以下几种用法:
#include <random>
size_t get_rand()
{
static thread_local std::mt19937 generator(time(0));
std::uniform_int_distribution<int> distribution(0, 10);
return distribution(generator);
}
Run Code Online (Sandbox Code Playgroud)
我想知道使用static thread_local而不是static在这里能带来什么好处。// 第一个static是多余的
据我所知,在第二种情况下,generator线程的生命周期结束之前。是否有其他共同点或特殊情况的好处/差异?