我试图将成员变量类型声明为派生类控制的东西 - 而不将类型作为模板传输。
#include <tuple>
#include <iostream>
#include <ostream>
using namespace std;
template<class DERIVED_TYPE>
struct haveChildren
{
const std::tuple<int, DERIVED_TYPE::innerContext > myChildren;
haveChildren(int a, char b) : myChildren(5, DERIVED_TYPE::innerContext{ a, b }) {}
friend ostream& operator<< (ostream& streamReceiver, const haveChildren<DERIVED_TYPE>& streamSender)
{
int myInt; int myChar;
std::tie(myInt, myChar) = std::get<1>(streamSender.myChildren);
return streamReceiver << "My int is " << myInt << " my char is " << ((char)myChar);
}
};
struct haveChildrenCharAndInt : public haveChildren<haveChildrenCharAndInt>
{
typedef std::tuple<char, int> innerContext;
haveChildrenCharAndInt() : haveChildren<haveChildrenCharAndInt>(10,'x') {}
};
int main(int argc, char* argv[])
{
cout << haveChildrenCharAndInt();
return 0;
}
那当然不能编译——但我希望你明白我想要做什么。
可以通过将类型作为模板参数传输来完成,如下所示:
template<class DERIVED_TYPE,typename A,typename B>
struct haveChildren
{
const std::tuple<int, std::tuple<A, B> > myChildren;
haveChildren(int a, char b) : myChildren(5, std::tuple<A, B> { a, b }) {}
friend ostream& operator<< (ostream& streamReceiver, const haveChildren<DERIVED_TYPE,A,B>& streamSender)
{
int myInt; int myChar;
std::tie(myInt, myChar) = std::get<1>(streamSender.myChildren);
return streamReceiver << "My int is " << myInt << " my char is " << ((char)myChar);
}
};
struct haveChildrenCharAndInt : public haveChildren<haveChildrenCharAndInt,char,int>
{
typedef std::tuple<char, int> innerContext;
haveChildrenCharAndInt() : haveChildren<haveChildrenCharAndInt,char,int>(10,'x') {}
};
int main(int argc, char* argv[])
{
cout << haveChildrenCharAndInt();
return 0;
}
但是这个解决方案并不好,因为类应该作为成员变量的类型是类,它们是在之后创建的。
你们中的任何人都知道一种设计或技巧,它可以让一个类型的成员变量在一个类从它继承之前不定义 - 而无需将类型作为模板参数传输?