【发布时间】:2015-06-04 19:03:35
【问题描述】:
我正在尝试将成员变量类型声明为派生类控制的东西 - 而不将类型作为模板传输。
#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;
}
但是这种解决方案并不好,因为类应该作为成员变量的类型是类,并且它们是在之后创建的。
你们中是否有人知道一种设计或技巧,可以让一个类型的成员变量在类从它继承之前不定义 - 无需将类型作为模板参数传输?
【问题讨论】:
-
你说的类型......是类并且是之后创建的是什么意思?定义
haveChildrenCharAndInt时,构成innerContext的类型需要完整,这样基类才能包含它们的实例。
标签: c++ templates c++14 crtp stdtuple