Skip to content

Conversation

DwarKapex
Copy link
Owner

OTUS HW3: print IP

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))
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Используя арифметику над указателем можно сильно упростить это выражение.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Вопрос:
А если входной аргумент value отрицателен, правильно ли будет произведено преобразование?

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Вопрос:
А если входной аргумент value отрицателен, правильно ли будет произведено преобразование?

Да. См. условие задания и первый тест в test_PrintIp.cpp

Copy link
Owner Author

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 {};
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Неудачное имя is_container. Может ввести в заблуждение.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Здесь тоже можно расширить диапазон принимаемых типов с помощью std::decay

Copy link
Owner Author

@DwarKapex DwarKapex Jan 14, 2021

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 отправлять

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Я (т.е. пользователь) по-прежнему захочу передать, например, std::unordered_map value.

Copy link
Owner Author

@DwarKapex DwarKapex Jan 15, 2021

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>
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Не очень ясно зачем вызывать std::decay_t. От каких случаев убережет? Не увидел в тестах.
Буду благодарен если проясните. Спасибо.

Copy link

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 в любых комбинациях квалификаторов.

Copy link

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)

https://wandbox.org/permlink/48ad8AdTSRPiuqux

Copy link

@azbyx azbyx Jan 15, 2021

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>
Copy link

@Xmiler Xmiler Jan 10, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Не способен оценить - к опциональной части не приступал. Сори )

@Xmiler
Copy link

Xmiler commented Jan 10, 2021

Хороший код. Спасибо!

Copy link

@azbyx azbyx left a 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))
Copy link

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>
Copy link

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 {};
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Здесь тоже можно расширить диапазон принимаемых типов с помощью std::decay

@DwarKapex DwarKapex changed the base branch from structure to main January 16, 2021 02:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants