我正在通过 Herb Sutter's
旅程:迈向更强大、更简单的 C++ 编程
结构绑定部分
为了理解这个概念。最好是写一个我试过但得到一些错误的程序
只是想尝试如何在具有私有数据的类上使用结构绑定。请忽略以下示例。如果您可以提供任何示例
#include<iostream>
#include<string>
using namespace std;
class foobar {
public:
foobar() { cout << "foobar::foobar()\n"; }
~foobar() { cout << "foobar::~foobar()\n"; }
foobar( const foobar &rhs )
{ cout << "foobar::foobar( const foobar & )\n"; }
void ival( int nval, string new_string ) { _ival = nval;s=new_string; }
private:
int _ival;
string s;
};
foobar f( int val,string new_string ) {
foobar local;
local.ival( val,new_string );
return local;
}
template<> struct tuple_element<0,foobar> { using type = int; };
template<> struct tuple_element<1,foobar> { using type = string; };
// 2. Now add get<> support (using C++17, because why not; it’s better
// than =delete’ing the primary get<> template and adding specializations)
template<int I>
auto get(const foobar&x) {
if constexpr(I == 0) return x._ival;//'_ival' is a private member of 'foobar'
else if constexpr(I == 1) return x.s;//'s' is a private member of 'foobar'
}
int main(){
foobar ml = f( 1024,"hello" );
auto [ n, s] = f( 1024,"hello" );//Cannot decompose non-public member '_ival' o
return 0;
}
错误
if constexpr(I == 0) return x._ival;//'_ival' 是 'foobar' 的私有成员
else if constexpr(I == 1) return xs;//'s' 是 'foobar' 的私有成员
auto [ n, s] = f( 1024,"hello" );//不能分解非公开
需要帮助
1.如果有人可以详细说明他在这些方面实际尝试做什么(请参阅提供的链接)
// 2. Now add get<> support (using C++17, because why not; it’s better
// than =delete’ing the primary get<> template and adding specializations)
template<int I>
auto get(const S&) {
if constexpr(I == 0) return x.i;
else if constexpr(I == 1) return string_view{x.c}; }
else if constexpr(I == 2) return x.d;
}
2.任何建议如何解决上述示例的错误