2

Решил поиграться со SFINAE и столкнулся с проблемой, что не могу узнать длину строки при помощи шаблонов, по крайней мере компилятор ругается. Можете ли подсказать, в чем моя ошибка?

#include <iostream>
#include <string>
#include <type_traits>

namespace detail
{
template<std::string& str, bool init = str.empty()>
struct is_empty : std::false_type
{};

template<std::string& str>
struct is_empty<str, true> : std::true_type
{};

template<std::string& str>
using is_empty_t = typename is_empty<str>::type;
}

int main()
{
   std::string str;
   std::cout << detail::is_empty_t<str>::type << std::endl;
}

Может я написал какой-то ужас. Можете подсказать, что конкретно не так?

4

1 ответ 1

1

Кажется, что использование SFINAE в данном случае избыточно. Достаточно наследоваться от bool_constant, которое параметризуется значением str.empty():

template<String str>
struct IsEmpty : std::bool_constant<str.empty()> {}

Но это, скорее, замечание, нежели ответ на Ваш вопрос.


В моем примере String это что-то вроде:

template<std::size_t N>
struct String
{
    constexpr explicit String(const char(&str)[N])
        : value()
    {
        for (std::size_t i = 0; i < N; ++i) value[i] = str[i];
    }

    char value[N];
};

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.