将SFML的RenderWindow对象传递给模板函数

时间:2019-03-20 12:06:54

标签: c++ templates sfml template-meta-programming

我是一名新手C ++程序员,但我不是专业人士。我对C ++中的模板感到困惑。

我正在使用SFML,可以创建一个窗口并进行处理。在下一步中,我决定编写一个模板函数以在关闭信号生成时对其进行处理。但我的代码无法编译。问题出在哪里?

#include <SFML/Graphics.hpp>
#include <iostream>

template <typename T>
void EventHandler(T& window) {
    std::cout << "Close event is made." << std::endl;
    window.close();
    std::cout << "Window is closed succesfully." << std::endl;
    break;
}

int main()
{
    sf::RenderWindow window(sf::VideoMode(512, 512), "SMFL Tutorial", sf::Style::Default);
    sf::Event events;

    while (window.isOpen())
    {
        while (window.pollEvent(events))
        {
            switch (events.type)
            {
            case events.Closed:
                EventHandler(window);
            default:
                std::cout << "Unkown Events are creating." << std::endl;
                break;
            }
        }
    }
    return 0;
}

1 个答案:

答案 0 :(得分:1)

您需要在函数中将break语句从函数移至case并正确使用sf::Event::EventType枚举:

#include <SFML/Graphics.hpp>
#include <iostream>

template <typename T>
void EventHandler(T& window) {
    std::cout << "Close event is made." << std::endl;
    window.close();
    std::cout << "Window is closed succesfully." << std::endl;
    /// break; <- From here
}

int main()
{
    sf::RenderWindow window(sf::VideoMode(512, 512), "SMFL Tutorial", sf::Style::Default);
    sf::Event events;

    while (window.isOpen())
    {
        while (window.pollEvent(events))
        {
            switch (events.type)
            {
            case sf::Event::Closed:
                EventHandler(window);
                break; /// <- To here
            default:
                std::cout << "Unkown Events are creating." << std::endl;
                break;
            }
        }
    }
    return 0;
}

此外,为什么需要模板功能?您的EventHandler函数可以引用sf::window来与sf::Windowsf::RenderWindow一起使用:

void EventHandler(sf::Window& window) {
    std::cout << "Close event is made." << std::endl;
    window.close();
    std::cout << "Window is closed succesfully." << std::endl;
}