我正在使用Stroustrup的包装器模板类:
template<class T, class Pref, class Suf>
class Wrap {
protected:
T* p;
int* owned;
void incr_owned() { if (owned) ++*owned; }
void decr_owned() { if (owned && --*owned == 0) { delete p; delete owned; } }
Pref prefix;
Suf suffix;
public:
Wrap(T& x, Pref pr, Suf su)
:p(&x), owned(0), prefix(pr), suffix(su) { }
Wrap(T* pp, Pref pr, Suf su)
:p(pp), owned(new int(1)), prefix(pr), suffix(su) { }
Wrap(const Wrap& a)
:p(a.p), owned(a.owned), prefix(a.prefix), suffix(a.suffix)
{ incr_owned(); }
我将其子类化以创建线程安全对象:
template<class DSP> class DspWrap : public Wrap<DSP, void(*)(), void(*)()> {
protected:
CriticalSection* criticalSection;
public:
DspWrap(DSP& x) : Wrap<DSP, void(*)(), void(*)()>(x, &DspWrap::prefix, &DspWrap::suffix) {
}
DspWrap(DSP* pp) : Wrap<DSP, void(*)(), void(*)()>(pp, &DspWrap::prefix, &DspWrap::suffix) { //compiler error here
}
但是在创建对象
DspWrap<PpmDsp> wrap = DspWrap<PpmDsp>(new PpmDsp());
的行中时,出现以下错误error C2664: 'Wrap<T,Pref,Suf>::Wrap(T &,Pref,Suf)' : cannot convert parameter 1 from 'PpmDsp *' to 'PpmDsp &'
但是,为什么调用了错误的构造函数?实际上,有一个
PpmDsp*
的构造函数,那么为什么要尝试调用PpmDsp&
?提前致谢
最佳答案
我不确定您要对成员进行初始化方面要做什么,但是您需要基类的适当构造参数,而基类成员*本身*并不是这样做的方法。
一旦我为prefix
和suffix
声明了两个实函数,其余的就起作用了,并且基本构造函数正确初始化了。由于我没有您对CriticalSection
或DSP
的定义,因此我不得不假冒该示例,但是....
#include <iostream>
typedef int CriticalSection;
template<class T, class Pref, class Suf>
class Wrap {
protected:
T* p;
int* owned;
void incr_owned() { if (owned) ++*owned; }
void decr_owned() { if (owned && --*owned == 0) { delete p; delete owned; } }
Pref prefix;
Suf suffix;
public:
Wrap(T& x, Pref pr, Suf su)
:p(&x), owned(0), prefix(pr), suffix(su) { }
Wrap(T* pp, Pref pr, Suf su)
:p(pp), owned(new int(1)), prefix(pr), suffix(su) { }
};
template<class DSP> class DspWrap : public Wrap<DSP, void(*)(), void(*)()> {
protected:
CriticalSection* criticalSection;
// implemenations of these
static void prefix_fn() {};
static void suffix_fn() {};
public:
DspWrap(DSP& x)
: Wrap<DSP, void(*)(), void(*)()>(x, &prefix_fn, &suffix_fn)
, criticalSection(new CriticalSection)
{
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
DspWrap(DSP* pp)
: Wrap<DSP, void(*)(), void(*)()>(pp, &prefix_fn, &suffix_fn)
, criticalSection(new CriticalSection)
{
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
};
struct MyDSP { };
int main()
{
MyDSP dsp;
DspWrap<MyDSP> wrap1(dsp);
MyDSP *dsp2 = new MyDSP;
DspWrap<MyDSP> wrap2(dsp2);
return 0;
}
输出量
DspWrap<MyDSP>::DspWrap(DSP &) [DSP = MyDSP]
DspWrap<MyDSP>::DspWrap(DSP *) [DSP = MyDSP]