小编kar*_*doc的帖子

为什么私有成员变量不允许使用decltype?

假设我有一个这样的类:

class Foo
{
  std::vector<int> bar;

public:
  std::vector<int>& get_bar() { return bar; }
};
Run Code Online (Sandbox Code Playgroud)

后来,我想要另一个与其他类型相同的变量bar.如果我能做到这一点,对我来说是有意义的:

decltype(Foo::bar) clone_of_bar;
Run Code Online (Sandbox Code Playgroud)

但这不起作用.编译器告诉我'std :: vector <int> Foo :: bar'是私有的.

所以我最终不得不使用这样的东西:

std::remove_reference<decltype(std::declval<Foo>().get_bar())>::type clone_of_bar;
Run Code Online (Sandbox Code Playgroud)

哪个有效,但看起来像是一团糟.也许有一种更容易的方法; 我不太确定.但我真正想知道的是为什么我不能只使用decltype(Foo::bar).为什么有人关心bar私人?这不像我实际上访问变量.

decltype是该语言的新功能.我只是不明白为什么它的设计不适用于私有变量.

c++ decltype c++11

12
推荐指数
2
解决办法
3471
查看次数

右值函数重载

我想重载一个函数,以便它以某种方式操作它的参数,然后返回对参数的引用 - 但如果参数不可变,那么它应该返回参数的操纵副本.经过多年的讨论,这就是我想出来的.

using namespace std;

string& foo(string &in)
{
    in.insert(0, "hello ");
    return in;
}

string foo(string &&in)
{
    return move(foo(in));
}

string foo(const string& in)
{
    return foo(string(in));
}
Run Code Online (Sandbox Code Playgroud)

这段代码似乎工作正常,但我很想知道是否有人能想到更好的方法来做到这一点.

这是一个测试程序:

int main(void)
{
    string var = "world";
    const string var2 = "const world";
    cout << foo(var) << endl;
    cout << var << endl;

    cout << foo(var2) << endl;
    cout << var2 << endl;

    cout << foo(var + " and " + var2) << endl;
    return …
Run Code Online (Sandbox Code Playgroud)

c++ rvalue-reference c++11

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

防止const成员函数更改成员数组

显然,仍允许const成员函数更改类成员指向的数据.这是我的意思的一个例子:

class MyClass
{
public:
  MyClass();
  int getSomething() const;
private:
  int* data;
};

// ... data = new int[10];, or whatever

int MyClass::getSomething() const
{
  data[4] = 3; // this is allowed, even those the function is const
  return data[4];
}
Run Code Online (Sandbox Code Playgroud)

如果不允许这样做,我更愿意.我应该如何定义"数据",以便"getSomething()const"不允许更改它?(但是允许非const函数改变它.)是否有某种"最佳实践"?也许std :: vector?

c++ const

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

标签 统计

c++ ×3

c++11 ×2

const ×1

decltype ×1

rvalue-reference ×1