gpt4 book ai didi

c++ - 默认模板参数

转载 作者:行者123 更新时间:2023-11-28 03:51:58 25 4
gpt4 key购买 nike

我正在测试一个属性系统,我想确保根类可以保存指向现有的最派生类的函数指针。结果,我得到了一些有用的东西。最派生类当前正在工作(RC2),但当前中间类(RC1)将出现编译错误。我希望能够实例化 RC1 和 RC2。我在创建 RC 时遇到的编译器错误是(对于 RC1<RC1> rc1test; 行)

error C2955: 'RC1' : use of class template requires template argument list

error C3203: 'RC1' : unspecialized class template can't be used as a template argument for template parameter 'PropertyOwner', expected a real type

我试着做 RC1<> rc1test;但这也无济于事。这是来源,有人有什么建议吗?

#include <iostream>
#include <map>
#include <string>
using namespace std;

template<class T, class BaseClass>
class RBase : public BaseClass
{
public:
typedef int (T::*GetFP)(void) const;

protected:
std::map<const char*, GetFP> mGetFPs;

};

class CBase
{

};

template<class PropertyOwner>
class RC1;

template<class PropertyOwner=RC1>
class RC1 : public RBase<PropertyOwner, CBase>
{
public:
int int1(void) const
{
return 1;
}

RC1()
{
mGetFPs.insert( pair<const char*, GetFP>("RC1I1I", &PropertyOwner::int1) );
};

virtual void inspection(void)
{
int test = 0;
}
};

class RC2 : public RC1<RC2>
{
public:
int int2(void) const
{
return 2;
}

RC2()
{
mGetFPs.insert( pair<const char*, GetFP>("RC2I2I", &RC2::int2) );
};

virtual void inspection(void)
{
int test = 0;
}
};

int main(void)
{
RC1<RC1> rc1test;

RC2 rc2test;
rc2test.inspection();

return(0);
}

最佳答案

如果您可以使用 boost,那么您也许可以使用 boost::function 和 boost::bind 来获得您想要的指针,从而获得更简洁的方法。

    template <typename BC>
class RBase : public BC
{
public:
typedef int FunctionSignature (void) const;
typedef boost::function<FunctionSignature> CallbackFunction;
protected:
std::map<const char*, CallbackFunction> mGetFPs;
};

class CBase
{
};

class RC1 : public RBase<CBase>
{
public:
RC1 ()
{
mGetFPs.insert ( std::make_pair ( "RC1I1I",
boost::bind ( &RC1::int1, this ) ) );
}
int int1(void) const { return 1; }
};


class RC2 : public RC1
{
public:
RC2 ()
{
mGetFPs.insert ( std::make_pair ( "RC2I2I",
boost::bind ( &RC2::int2, this ) ) );
}
int int2(void) const { return 2; }
};

事实上,您可以将具有适当签名的任何函数分配给 boost::function,甚至可以使用 boost::bind 来调整具有附加参数的函数(见下文)。

    class RC3 : public RC1
{
public:
RC3 ()
{
mGetFPs.insert ( std::make_pair ( "RC3I3I",
boost::bind ( &RC3::intN, this, 3 ) ) );
}
int intN(int n) const { return n; }
};

关于c++ - 默认模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5172231/

25 4 0
文章推荐: c++ - WTL/Winapi 消息处理程序中的模态窗口
文章推荐: html -
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com