简体   繁体   中英

How to pass Ref or Ptr of a templated class with non-type Parameters

Say I have this class template with two non-type parameters:

template<uint16_t tValA, uint8_t tValB> class TClass
    {
         ...
    };

If possible. How can I pass either a reference or pointer to a function, such as:

TClass<300,4> Instance1;    
TClass<340,5> Instance2;

aFunction(Instance2);

void aFunction(TClass<uint16_t,uint8_t>& _Instance)
{
    _Instance.DoSomething();
}

With a template function:

template <uint16_t N1,uint8_t N2>
void aFunction(TClass<N1, N2>& instance)
{
    instance.DoSomething();
}

TClass<300,4> and TClass<340,5> are distinct types without a common base class ( TClass does not count), so they can't be passed to the same function, unless you template it as well:

template <uint16_t tValA, uint8_t tValB>
void aFunction(TClass<tValA, tValB>& _Instance)
{
    _Instance.DoSomething();
}

You can't because TClass<300,4> and TClass<340,5> are different types.

But if you have common parent class, like,

class ParentClass
{
public:
    virtual void DoSomething();
};

template<uint16_t tValA, uint8_t tValB>
class TClass : public ParentClass
{
    //...
};

Then you can have argument with that parent class.

void aFunction(ParentClass& _Instance)
{
    _Instance.DoSomething();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM