简体   繁体   中英

Forward declarations and cross-referencing in tuples

There are plenty of questions regarding C++ forward declarations in StackOverflow, but nothing I found addresses this issue.

Consider the following code:

struct Record1; // Forward declaration.
struct Record2; // Forward declaration.

struct Record1 {int a; Record2 *r2;};
struct Record2 {int b; Record1 *r1;};

It's compilable and usable. Now, say I would like to use tuples, instead of structs. Is that possible? It seems I can't avoid needing some sort of (an illegal) forward declaration for typedefs, eg:

class Record1;
class Record2;

using Record1 = std::tuple<int, Record2*>; // No go. Conflicting declaration.
using Record2 = std::tuple<int, Record1*>; // Same here.

I've tried several approaches, including desperately abusing late template instantiation, but with no success. I would appreciate any ideas.

Thanks!

Abusing public inheritance is a way to get what you want:

#include <iostream>
#include <tuple>

class Record1;
class Record2;

class Record1: public std::tuple<int, Record2*> { using base = std::tuple<int, Record2*>; using base::base; };
class Record2: public std::tuple<int, Record1*> { using base = std::tuple<int, Record1*>; using base::base; };

int main() 
{
    Record1 r1 = std::make_tuple(0, nullptr);        
    std::cout << (std::get<0>(r1) == 0) << (std::get<1>(r1) == nullptr);
}

Live Example .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM