c++,真有趣啊
由于笔者的水平不太行,在这个贴里记录一些自己犯过的不太容易被发现的错误
20221029
基类
class CBase
{
public:
virtual ~CBase() {}
private:
virtual bool __fooV() { return true; }
friend class CFactory;
};
继承类
class CDerived : public CBase
{
private:
virtual bool __fooV(int x) { return x > 100; }
friend class CFactory;
};
工厂类
class CFactory
{
public:
template <typename TDerived, class... TArgs>
requires std::is_base_of<CBase, TDerived>::value
static TDerived* createResource(TArgs&&... vArgs)
{
TDerived* pDerived = new TDerived();
assert(pDerived);
CBase* pBase = pDerived;
bool IsInitSucceed;
if (sizeof...(vArgs) > 0) IsInitSucceed = pDerived->__fooV(std::forward<TArgs>(vArgs)...);
else IsInitSucceed = pBase->__fooV();
if (!IsInitSucceed)
{
delete pDerived;
pDerived = nullptr;
}
return pDerived;
}
};
CDerived* pDerived = CFactory::createResource<CDerived>();
期望:在函数 CFactory::createResource 的实例化中,由于模板参数包的大小为0,所以最后当然会执行else分支的部分,那么不管if部分的话,编译肯定是能顺利通过的吧?
事实:编译的时候可不会管哪些函数会不会被执行到,CBase::__fooV 对 CDerived 不可见,自然编译就失败了。
修改方法:在 CDerived 中override __fooV()
20230715
在OpenGL的Compability上下文中,绘制point sprite出错,在Fragment Shader中获取到的gl_PointCoord均为0
解决方案:在Compability上下文中需要调用 glEnable(GL_POINT_SPRITE)