[英]Use templated object within a templated class with different sets of template parameters
[英]Set pointer to templated class in class with different template
我想在 C++ 中創建一個 class,它可以存儲指向另一個 class 的指針。我還希望指針始終從nullptr
開始(最好不在構造函數中)。
我有以下示例。
template <class one>
class BaseA
{
public:
~BaseA(){}
void computeSomething(){std::cout << "function1 is being called" << std::endl;}
};
template <class two>
class BaseB
{
public:
~BaseB(){}
template<class one>
BaseA<one>* myPtr = nullptr;
template<class one>
void setPtr(BaseA<one>& obj ){ myPtr = &obj; }
};
但是在編譯時我得到了錯誤:
error: data member ‘myPtr’ cannot be a member template
我希望得到的最終結果是:
template<class two>
void iAmAFunction(BaseB<two>& obj)
{
obj.myPtr->computeSomething();
}
int main(int argCount, char *args[])
{
BaseB<int> one;
BaseA<double> two;
one.setPtr(two);
iAmAFunction<int>(banana1);
std::cout << "End " << std::endl;
}
我怎樣才能解決這個問題?
我想在 C++ 中創建一個 class,它可以存儲指向另一個 class 的指針。我還希望指針始終從 nullptr 開始
那是:
class BaseA {
public:
int a = 2;
};
class BaseB {
public:
BaseA* myPtr = nullptr;
void setPtr(BaseA* obj ){ myPtr = obj; }
};
我想要一個模板化 class (B) 來保存指向另一個模板化 class A(不同模板)的指針。
沒有指向模板的指針。 您可以存儲指向 object 的指針。其類型可以是 class 模板的實例化。 但是,如錯誤所述,沒有成員模板。 如果BaseA
是 class 模板,那么您可以為模板的所有實例化引入一個公共基礎並存儲指向它的指針:
class Base {};
template <typename T>
class BaseA : Base{
public:
int a = 2;
};
class BaseB {
public:
Base* myPtr = nullptr;
void setPtr(Base* obj ){ myPtr = obj; }
};
現在BaseB
也可以是 class 模板,這不會改變任何東西。
這是可能的解決方案。 如果您有其他意見,我們將不勝感激。
class Base {
void virtual someVirtualFunction(){}
};
template <class one>
class BaseA: public Base
{
public:
~BaseA(){}
void computeSomething(){std::cout << "function1 is being called" << std::endl;}
int a = 2;
};
template <class two>
class BaseB
{
public:
~BaseB(){}
Base* myPtr = nullptr;
void setPtr(Base& obj ){ myPtr = &obj; }
};
template<class two>
void iAmAFunction(BaseB<two>& obj)
{
BaseA<double>* check = dynamic_cast<BaseA<double>*>(obj.myPtr);
if (!check)
{
throw std::runtime_error("Not the correct type");
}
check->computeSomething();
}
int main(int argCount, char *args[])
{
BaseB<int> obj1;
BaseA<double> obj2;
obj1.setPtr(obj2);
iAmAFunction<int>(obj1);
std::cout << "End " << std::endl;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.