-
Notifications
You must be signed in to change notification settings - Fork 0
Print ip #4
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
1. For tuple: check that all types are the same 2. if contexpr for tuple print
size_t type_size = sizeof(T); | ||
std::string result; | ||
for (size_t i = type_size; i > 0 ; --i) { | ||
result += std::to_string((value >> (8*(i-1)) & 0xFF)) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Используя арифметику над указателем можно сильно упростить это выражение.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Вопрос:
А если входной аргумент value отрицателен, правильно ли будет произведено преобразование?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Вопрос:
А если входной аргумент value отрицателен, правильно ли будет произведено преобразование?
Да. См. условие задания и первый тест в test_PrintIp.cpp
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Используя арифметику над указателем можно сильно упростить это выражение.
Вообще не уверен, что арифметика будет работать быстрее. Да, будет работать, но это лишние такты. Побитовые операции, ИМХО, надежнее в плане выскочить за пределы числа случайно. Но это дело вкуса, конечно же.
template<typename T> | ||
struct is_container: std::false_type {}; | ||
template<typename ...T> | ||
struct is_container<std::vector<T...>>: std::true_type {}; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Неудачное имя is_container
. Может ввести в заблуждение.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Здесь тоже можно расширить диапазон принимаемых типов с помощью std::decay
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Неудачное имя
is_container
. Может ввести в заблуждение.
У меня почти всегда с адекватными именами переменных плохо. Можно попробовать is_stl_container
, но просто is_container
расширяемо на собственные контейнеры
Здесь тоже можно расширить диапазон принимаемых типов с помощью std::decay
Да, поправлю перед тем как в master отправлять
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Я (т.е. пользователь) по-прежнему захочу передать, например, std::unordered_map value
.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Я (т.е. пользователь) по-прежнему захочу передать, например,
std::unordered_map value
.
А вот фигушки тебе, можешь хотеть сколько хочешь =)). Ты, как пользователь, здесь человек бесправный и этого сделать не сможешь, потому что нет специализации unordered_map
(я прогер, чО хочу, то и делаю =)) А вот если ты заказчик, то надо было это в ТЗ описать. Но ТЗ было составлено ОТУСом, так что пока обломись =))
* \param[out] string with result | ||
*/ | ||
template<typename T> | ||
std::enable_if_t<std::is_same_v<std::decay_t<T>, std::string>, std::string> |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Не очень ясно зачем вызывать std::decay_t
. От каких случаев убережет? Не увидел в тестах.
Буду благодарен если проясните. Спасибо.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
std::decay_t, чтобы данная функция включалась не только когда T = std::string, но и когда строка является константной и/или ссылылочной и/или volatile в любых комбинациях квалификаторов.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
https://en.cppreference.com/w/cpp/types/is_same
If T and U name the same type (taking into account const/volatile qualifications)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Это для случая когда аргумент является xvalue-ссылкой:
template<typename T>
std::enable_if_t<std::is_same_v<std::decay_t<T>, std::string>, void> foo(T&& value) {
std::cout << value << std::endl;
}
Здесь уже без std::decay не прокатит.
* \param[in] value ip address in tuple format | ||
* \param[out] string with result | ||
*/ | ||
template <typename T, typename... Tail> |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Не способен оценить - к опциональной части не приступал. Сори )
Хороший код. Спасибо! |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Хорошая лаконичная работа.
Спасибо за возможность ознакомиться.
size_t type_size = sizeof(T); | ||
std::string result; | ||
for (size_t i = type_size; i > 0 ; --i) { | ||
result += std::to_string((value >> (8*(i-1)) & 0xFF)) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Вопрос:
А если входной аргумент value отрицателен, правильно ли будет произведено преобразование?
* \param[out] string with result | ||
*/ | ||
template<typename T> | ||
std::enable_if_t<std::is_same_v<std::decay_t<T>, std::string>, std::string> |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
std::decay_t, чтобы данная функция включалась не только когда T = std::string, но и когда строка является константной и/или ссылылочной и/или volatile в любых комбинациях квалификаторов.
template<typename T> | ||
struct is_container: std::false_type {}; | ||
template<typename ...T> | ||
struct is_container<std::vector<T...>>: std::true_type {}; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Здесь тоже можно расширить диапазон принимаемых типов с помощью std::decay
OTUS HW3: print IP