与C ++模板有点混淆

时间:2014-03-12 00:10:12

标签: c++ templates

我有以下内容:

        extern Keyboard keyboard;

        enum DEVICETYPE
        {
            KEYBOARD,
            MOUSE,
            CONTROLLER,
            TOUCH
        };

        template <typename T>
        class PlayerInputDevice
        {
        public:
            void SetDevice( DEVICETYPE deviceType )
            {
                switch( deviceType )
                {
                case KEYBOARD:
                    Device = &keyboard;
                    break;
                }
            }

            T Device;
        };

我收到编译错误:

Error   1   error C2955: 'Game::Model::Input::PlayerInputDevice' : use of class template requires template argument list (Concrete\Player.cpp)  c:\users\james\documents\visual studio 2013\projects\games\jimmy\model\concrete\player.h    29  1   Model
Error   2   error C2512: 'Game::Model::Input::PlayerInputDevice' : no appropriate default constructor available c:\users\james\documents\visual studio 2013\projects\games\jimmy\model\concrete\player.cpp  8   1   Model
Error   6   error C2955: 'Game::Model::Input::PlayerInputDevice' : use of class template requires template argument list    c:\users\james\documents\visual studio 2013\projects\games\jimmy\model\concrete\player.h    29  1   Game
        7   IntelliSense: argument list for class template "Game::Model::Input::PlayerInputDevice" is missing   c:\Users\James\Documents\Visual Studio 2013\Projects\Games\Jimmy\Model\Concrete\Player.h    29  5   Model

我不确定我是否正确理解了这一点?

我希望能够说出这样的话:

class Player
{
public:    
    PlayerInputDevice PlayerInputDevice;
}

...

player.PlayerInputDevice.SetDevice( KEYBOARD );
player.PlayerInputDevice.IsUpPressed();

1 个答案:

答案 0 :(得分:2)

您的PlayerInputDevice是一个模板类,因此要使用它,您需要一个模板参数,正如编译器所说。 E.g。

class Player
{
public:    
    PlayerInputDevice<Device> playerInputDevice;
};

其中Device是适合您的应用的某种类型。

注意我已将数据成员的名称更改为playerInputDevice;它不能与班级名称相同。