Как бороться с такими проблемами из шаблонов, используя std :: enable_if в cpp - PullRequest
0 голосов
/ 19 января 2020

Я пытаюсь создать функцию, которая записывает любой элемент или последовательность элементов в выходной поток. Я делаю это с помощью шаблонов, используя std :: enable_if. Существует две версии функции: первая предназначена для работы с секвенциями, а вторая - для отдельных элементов, таких как char. Код ниже:

#include <iostream>
#include <list>
#include <type_traits>
#include <array>

const int maximum_array_length = 10;
const int maximum_element_length = 50;

/*below are functions which must write any element or their sequences to an any output stream*/

/*template function for non arithmetic types like char and so on.*/
template <typename T, typename O, typename std::enable_if<std::negation<typename std::is_arithmetic<T>::value>::value, bool>::type = 0>
void cstoio(T container, O& out) {
    for (auto& i : container) {
        if (!i.empty() && *i.begin()) {
            for (auto& j : i)
                if (j)
                    out << j;

            out << '\n';
        }
    }
}

/*same function but for arithmetic types*/
template <typename T, typename O, typename std::enable_if<std::is_arithmetic<T>::value, bool>::type = 0>
void cstoio(T ae, O& out) {
    out << ae << '\n';
}

/*test function that launchs cstoio-function 3 times with different arguments*/
void test_f() {

    /*create arrays of chars*/
    std::array<char, maximum_element_length> ca1{ "aaa" };
    std::array<char, maximum_element_length> ca2{ "bbb" };
    std::array<char, maximum_element_length> ca3{ "ccc" };
    std::array<char, maximum_element_length> ca4{ "  " };
    std::array<char, maximum_element_length> ca5{ " ddd" };

    /*create an array of arrays of chars*/
    std::array<std::array<char, maximum_element_length>, maximum_array_length> a{ ca1, ca2, ca3, ca4, ca5 };

    /*create a list of strings*/
    std::list<std::string> l{ "abc","", " " ,"zzz", "end" };

    /*test launchs*/
    cstoio(a, std::cout); //launch with an array
    cstoio(l, std::cout); //launch with a list
    cstoio('a', std::cout); //launch with a single char

}

Но я получаю несколько ошибок во время компиляции:

Severity    Code    Description Project File    Line    Suppression State
Error   C2664   'void cstoio(char,std::ostream)': cannot convert argument 1 from 'std::array<std::array<char,50>,10>' to 'char' HelloWorld  E:\Studying\Programming\Cpp\Repos\NiceWeather\HelloWorld\Header.h   43  

Severity    Code    Description Project File    Line    Suppression State
Error   C2664   'void cstoio(char,std::ostream)': cannot convert argument 1 from 'std::list<std::string,std::allocator<_Ty>>' to 'char'
        with
        [
            _Ty=std::string
        ]   HelloWorld  E:\Studying\Programming\Cpp\Repos\NiceWeather\HelloWorld\Header.h   44  


Severity    Code    Description Project File    Line    Suppression State
Error (active)  E0304   no instance of overloaded function "cstoio" matches the argument list   HelloWorld  E:\Studying\Programming\Cpp\Repos\NiceWeather\HelloWorld\Header.h   48  

Severity    Code    Description Project File    Line    Suppression State
Error (active)  E0304   no instance of overloaded function "cstoio" matches the argument list   HelloWorld  E:\Studying\Programming\Cpp\Repos\NiceWeather\HelloWorld\Header.h   49  

1 Ответ

1 голос
/ 19 января 2020

Ваш std::negation вызов неверен. Сделать это

std::enable_if<std::negation<std::is_arithmetic<T>>::value, bool>::type

Или просто

std::enable_if<!std::is_arithmetic<T>::value, bool>::type

Демо

...