小编mou*_*_00的帖子

返回 auto&& 和 decltype(auto) 有什么区别?

我正在尝试制作模板包装函数,该函数应该转发参数并返回值。我无法决定使用什么auto&&decltype(auto)返回类型更好。我读过 Scott Meyers 的文章,并理解与不剥离 ref_qualifiersdecltype(auto)相比,有必要返回。auto据我了解,同样的论点适用于使用auto&&over auto。现在我有以下问题:

  1. 我对吗,我们返回对象的引用之间decltype(auto)和何时没有区别?auto&&
  2. 如果我们返回对象,会发生什么rvalue,例如:return int{};?返回值会是悬空引用吗?
  3. decltype(auto)和 和有什么区别auto&&?什么更适合作为远期回报类型?

c++ return-type c++14 forwarding-reference decltype-auto

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

为什么没有调用 move-constructor?

我有以下代码:

#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()我不明白为什么即使接受右值引用,复制构造函数也优于移动构造函数。

c++ rvalue lvalue rvalue-reference c++11

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

如何获取模板类模板参数?

我有一个模板类,想知道当模板类变量用作函数的模板参数时如何获取模板类变量类型。我尝试执行以下操作

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

c++ templates

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

在 .cpp 文件中使用一次 pragma

最近阅读一些代码时,我遇到了几个包含 #pragma once在文件开头的 .cpp 文件。我知道它通常在 .h 文件中用作防护。

在什么情况下#pragma once应该/可以/必须在 .cpp 文件中使用?

c++ pragma

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

将 static thread_local 与 std::mt19937 一起使用有什么好处?

我见过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线程的生命周期结束之前。是否有其他共同点或特殊情况的好处/差异?

c++ static thread-local mt19937

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