Let's suppose I have a class with a private method is_escape
which check if an input string is and ANSI escape sequence. This method is then used in another public method, into an if/else condition:
#include <string>
enum class ANSI { first, generic };
template <class T_str>
class foo
{
private:
template <typename T>
static constexpr bool is_escape( const T& str, ANSI&& flag ) { /* implementation */ }
public:
template <class T>
void public_method( T str ) // T can be also an int, double etc...
{
if ( is_escape( str ) ) { /* do something */ }
}
};
The implementation of the is_escape
method is the following:
#include <string>
#include <type_traits>
template <typename T>
static constexpr bool is_escape( const T& str, ANSI&& flag )
{
if constexpr( std::is_convertible_v <T, std::basic_string_view<T_str>> && ! std::is_same_v<T, std::nullptr_t> )
{
switch( flag )
{
case( ANSI::first ):
{
return ( ! std::basic_string_view<T_str>( str ).rfind( "\033"s, 0 ) ) &&
( std::basic_string_view<T_str>( str ).length() < 7 );
}
case( ANSI::generic ):
{
return ( std::basic_string_view<T_str>( str ).find( "\033"s ) != std::basic_string_view<T_str>::npos );
}
}
}
return false;
}
Is there a better way to write the method in order to improve its performances (in C 17)? Thanks.
CodePudding user response:
At the end, I improved the performances of the function with this signature:
template <typename T>
static constexpr bool is_escape( const T& str, const ANSI& flag )
{
if constexpr( std::is_convertible_v <T, std::basic_string_view<T_str>> && ! std::is_same_v<T, std::nullptr_t> )
{
switch( flag )
{
case( ANSI::first ):
{
return ( std::basic_string_view<T_str>( str ).length() < 7 ) && ( str[0] == '\033' );
}
case( ANSI::generic ):
{
return ( std::basic_string_view<T_str>( str ).find( '\033' ) != std::basic_string_view<T_str>::npos );
}
}
}
return false;
}