简体   繁体   中英

How can I implement system-specific functions without macros in modern C++

JetBrains ReSharper for C++ has told me to replace something like

#ifdef _WIN32
#    define cls system("cls")
#else // Assuming Unix
#    define cls system("tput clear")
#endif // _WIN32

with constexpr template functions.

However, I have tried to use SFINAE via std::enable_if_t<_WIN32> , but I'm getting errors saying "cannot overload functions distinguished by return type alone" (admittedly, I was not using a template function, but instead using enable_if for the return type).

Besides using enable_if as the return type, I don't know how to use constexpr template functions to implement what the preprocessor would do.

In a more general sense, I would like to be able to enable function overloads based on compile-time booleans that don't rely on other template parameters.

Thanks in advance!

You don't want enable_if , which is for cases where you might need to make decisions at compile time based on type parameters, etc.

The preprocessor is appropriate here, though it might be cleaner to use ordinary functions than macros.

#ifdef _WIN32
void cls() { system("cls"); }
#else // Assuming Unix
void cls() { system("tput clear"); }
#endif // _WIN32

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM