I am a newbie C++ programmer, and I am not a professional. I am so confused with the template in C++.
I was working with SFML and I could create a window and handle it. In the next step, I decided to write a template function to handle the close signal when it is generated. but my code doesn't compile. where is the problem?
#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;
}
You need to move the break statement from your function to case in the switch and properly use the sf::Event::EventType
enum :
#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;
}
Moreover, why do you need a template function? Your EventHandler
function can take a reference to a sf::window
to work either with sf::Window
and sf::RenderWindow
:
void EventHandler(sf::Window& window) {
std::cout << "Close event is made." << std::endl;
window.close();
std::cout << "Window is closed succesfully." << std::endl;
}