小编mg8*_*g84的帖子

将"this"作为右值返回

正如预期的那样,以下代码不会编译

#include <iostream>

class A
{

  public:

    A() = default;
    ~A() = default;

    A(const A&) = delete;
    A(A&&) = delete;

    A& operator=(const A&) = delete;
    A& operator=(A&&) = delete;

    A& operator<<(const int i)
    {
      std::cout << "operator<< called" << std::endl;
      return *this;
    }

};

void foo(A&& a)
{
  std::cout << "foo called" << std::endl;
}

int main()
{
  A a; a << 14;
  foo(std::move(a)); // works fine

  foo(A() << 14);    // does not compile

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

将A类改为

class A …
Run Code Online (Sandbox Code Playgroud)

rvalue-reference this-pointer c++11

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

在c ++中检查运行时的可转换性

在c ++中,隐式地完成了不同类型的转换.例如,int可以将类型的对象分配给const int(如下面代码中主函数的第一行中所做的那样).

现在我想检查运行时的可转换性,因为我有一个可以添加类型的结构,后来我想检查给定类型,如果结构中存储的类型之一可以转换为给定类型.

这是我到目前为止提出的:

#include <iostream>
#include <vector>

struct bar { virtual void dummy() {} };
template<typename T> struct foo : public bar { virtual void dummy() {} };

int main() {

    int i1 = 1;
    const int i2 = i1;

    std::vector<bar*> bars;
    bar* t1 = new foo<int>; bars.push_back(t1);
    bar* t2 = new foo<int const>; bars.push_back(t2);

    foo<int const>* t3 = dynamic_cast<foo<int const>*>(bars[0]);
    std::cout << t3 << std::endl;

    foo<int const>* t4 = dynamic_cast<foo<int const>*>(bars[1]);
    std::cout << …
Run Code Online (Sandbox Code Playgroud)

c++ type-conversion

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

具有模板化构造函数以及复制和移动构造函数的类

这个问题是这个问题的后续:模板化类模板化构造函数的显式模板专业化另一个问题中给出的答案当然是正确的,但结果证明我并没有问我想问什么 - 所以这里是一个新问题:

考虑以下代码:

template<typename First, typename ... Rest> class var {
    public:

    var() {
        std::cout << "default" << std::endl;
    }

    var(const var& v) {
        std::cout << "copy" << std::endl;
    }

    var(var&& v) {
        std::cout << "move" << std::endl;
    }

    template<typename T>
    var(const T& t) {
        std::cout << "general lvalue" << std::endl;
    }


    template<typename T>
    var(T&& t) {
        std::cout << "general rvalue" << std::endl;
    }

};


int main()
{
    var<int> i0; // expect 'default' -> get …
Run Code Online (Sandbox Code Playgroud)

c++ templates constructor

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

在 requires 子句中访问私有成员

考虑以下程序:

#include <iostream>

template<typename T> void f1(T& v)
{
  std::cout << "f1: can call g" << std::endl;
  v.g();
}

template<typename T> void f2(T& v) requires requires (T& v) { v.g(); }
{
  std::cout << "f2: can call g" << std::endl;
  v.g();
}

template<typename T> void f2(T&) requires (!requires (T& v) { v.g(); })
{
  std::cout << "f2: cannot call g" << std::endl;
}

class A
{

public: // if commented out, f2 will not call g anymore

  void g()
  { …
Run Code Online (Sandbox Code Playgroud)

c++ c++-concepts c++20

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