Reputation: 81
I have a template class, like this:
template <typename _Tp>
class CLayer{
public:
void AddLayer(CLayer *_layer);
private:
_Tp m_data;
CLayer *m_layer;
};
And then I want to add a double layer to a int layer.
int main()
{
CLayer<double> dlayer;
CLayer<int> ilayer;
ilayer.AddLayer(dlayer); // this expression is wrong;
// here, the AddLayer function is
// void CLayer<int>::AddLayer(CLayer<int> *_layer);
return 0;
}
How to implement that.
I know I can convert type CLayer<double> *
to CLayer<int> *
, but I will use the data in the future, I have to know the data type is double type.
Upvotes: 0
Views: 56
Reputation: 218323
There is name injection, so your code is:
template <typename T>
class CLayer
{
public:
void AddLayer(CLayer<T>* layer);
private:
T m_data;
CLayer<T>* m_layer;
};
You have to do some changes. Possible solution could be:
template <typename T, typename Next = void>
class CLayer
{
public:
void AddLayer(Next* layer);
private:
T m_data;
Next* m_layer = nullptr;
};
And then
CLayer<double> dlayer;
CLayer<int, CLayer<double>> ilayer;
ilayer.AddLayer(dlayer);
Upvotes: 2
Reputation: 133669
You can't do this since a template type is not a type without a template argument. This implies that CLayer
is not an usable type until you specify its template argument, it can't be used alone like you're doing.
To solve your problem without introducing variadic templates you can use inheritance, but this will force you to use the data only from inside the class itself (or provide some hacky mechanics to obtain it), eg:
class CLayer {
public:
void AddLayer(CLayer *_layer);
protected:
CLayer *m_layer;
};
template<typename _Tp>
class CLayerWithData : public CLayer {
protected:
_Tp m_data;
};
CLayer* intLayer = new CLayerWithData<int>();
CLayer* doubleLayer = new CLayerWithData<double>();
doubleLayer->AddLayer(intLayer);
Upvotes: 1