gpt4 book ai didi

c++ - 在它自己的指针上模板化一个类?

转载 作者:太空狗 更新时间:2023-10-29 20:23:10 27 4
gpt4 key购买 nike

我想在它自己的指针上模板化一个类。我该怎么做?

template <typename RefType, typename X>
class Foo {
public:
RefType ptr;
X val;
};
typedef Foo<Foo*, int> Type1;
typedef Foo<std::list<Foo>::iterator itr, int> Type2;

基本上,RefType 是这样一种类型,RefType 上的 operator * 会给我一个类 Foo 的实例。

关于如何在 C++ 中执行此操作的任何想法?

编辑:- 为我这样做的原因提供一些动力,我希望能够在下游客户端代码中这样做:-

void clientFunc(Type1& x) {
Type1 partner_x = *(x.partner);
}

事先不知道 x.partner 的类型。即 x.partner 可以是指向标准模板类的指针或迭代器。

这是一个非常晦涩的用例,我可以不用它,但代码看起来会更加优雅。

最佳答案

使用基类怎么样?

class Base {};

template <typename RefType, typename X>
class Foo : public Base
{
public:
RefType ptr;
X val;
};
typedef Foo<Base*, int> Type1;

int main()
{
Base* p = new Type1;
Type1* pt = static_cast<Type1*>(p);
pt->val = 3;
pt->ptr = new Type1;
(static_cast<Type1*>(pt->ptr))->val = 5;

// delete etc.
return 0;
}

您可以通过在 Base 类中引入适当的虚函数来跳过转换。

编辑

template<typename T>
class Base{
public:
virtual Base<T>*& get_ptr() = 0;
virtual T& get_val() = 0;
};

template <typename RefType, typename X>
class Foo : public Base<X>
{
public:
RefType ptr;
X val;

Base<X>*& get_ptr()
{
return ptr;
}

X& get_val()
{
return val;
};

};
typedef Foo<Base<int>*, int> Type1;
typedef Base<int> BaseType;

int main()
{
BaseType* p = new Type1;
p->get_ptr() = new Type1;
p->get_val() = 5;

// delete etc.
return 0;
}

关于c++ - 在它自己的指针上模板化一个类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34362879/

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