gpt4 book ai didi

c++ - 初始化嵌套模板类

转载 作者:搜寻专家 更新时间:2023-10-31 01:35:50 26 4
gpt4 key购买 nike

我有很多模板类,它们以任意顺序一起工作(共享相同的概念)。

假设我有:

template<typename T>
class A {
T t_;
public:
void call() {
// Do something.
t_.call();
}
};

template<typename T, typename U>
class B {
T t_;
U u_;
public:
void call() {
// Do something.
t_.call();
// Do something.
u_.call();
}
};

class C {
public:
void call() {
// Do something.
}
};

我有以下实例化类:

using Foo = A<B<A<C>,C>>;

让我们假设,C 可能需要一个特殊的构造函数(或初始化函数)才能工作。我只在运行时知道的事情。

struct C {
void init(int);
void call();
};

我应该如何初始化 Foo?或者任何其他嵌套类组合?

我目前的解决方法是将 C 定义为:

template<typename I>
struct C {
C() : var_(I::get())
void call();
};

并在一个函数中创建 Foo:

int main()
{
int i = 0;

struct HelperC1 {
static int get(bool set = false, int value = 0) {
static int value_ = value;
if (set) value_ = value;
return value_;
}
} helperC1;

struct HelperC2 {
static int get(bool set = false, int value = 0) {
static int value_ = value;
if (set) value_ = value;
return value_;
}
} helperC2;

helperC1.get(true, i);
helperC2.get(true, i+1);

A<B<A<C<HelperC1>>,C<HelperC2>>> foo;
foo.call();

return 0;
}

Live example.

你看,这个解决方法不是很方便。另一种方法是使用参数调用 Foo 的第一个构造函数并将它们重定向到 C 但这对于不同的类组合非常糟糕,例如:

using Bar = A<B<A<C>,<B<B<A,C>,C>>>;

问题:如何使用运行时参数初始化嵌套(模板)类(更好/以更好、更干净的方式)?

最佳答案

您可以使用指针并使用已构造和初始化的对象构建 foo。即:

未经测试的代码

template<typename T>
class A {
T* t_;

public:
A(T* valptr) : t_(valptr){}
~A(){ delete t_ ; }

void call() {
// Do something.
t_.call();
}
};

template<typename T, typename U>
class B {
T* t_;
U* u_;

public:
B(T* val1ptr, U* val2ptr):t_(val1ptr), u_(val2ptr){}
~B(){delete val1ptr; delete val2ptr;}

void call() {
// Do something.
t_->call();
// Do something.
u_->call();
}
};

class C {
private:
int x_;
public:
C(int x):x_(x){}
void call() {
// Do something.
}
};

用法:

A<B<A<C>,C>> foo( new B<A<C>,C>(new A<C>(new C(3) ), new C(3) ) );

关于c++ - 初始化嵌套模板类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36666800/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com