Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск  
 
 
Рейтинг 5.00/5: Рейтинг темы: голосов - 5, средняя оценка - 5.00
Любитель чаепитий
 Аватар для GbaLog-
3745 / 1801 / 566
Регистрация: 24.08.2014
Сообщений: 6,020
Записей в блоге: 1

Сломался шаблон класса ini_file

22.08.2016, 14:06. Показов 1083. Ответов 24
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Добрый день. В общем изучал я себе шаблоны, изучал, и вдруг решил попробовать переписать свой старый класс ini_file, чтобы он мог работать не только с std::string, но и с std::wstring. Написал я, конечно, говнокод, но мне в голову не идет, почему выдает ошибку о том, что такой специализации нет и как её исправить?

Вот код:
ini.hpp

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
/////////////////////////////////////////////////////////////////////////////////////////
#include <regex>
#include <string>
#include <vector>
#include <utility>
#include <fstream>
/////////////////////////////////////////////////////////////////////////////////////////
namespace tools
{
    /////////////////////////////////////////////////////////////////////////////////////
    struct Std_IO
    {
        using Str_type          = std::string;
        using Fily_type         = std::fstream;
        using Input_file_type   = std::ifstream;
        using Output_file_type  = std::ofstream;
    };
    /////////////////////////////////////////////////////////////////////////////////////
    struct Wstd_IO
    {
        using Str_type          = std::wstring;
        using Fily_type         = std::wfstream;
        using Input_file_type   = std::wifstream;
        using Output_file_type  = std::wofstream;
    };
    /////////////////////////////////////////////////////////////////////////////////////
    template< typename IO_type >
    using ini_map = std::vector<
                        std::pair<
                            typename IO_type::Str_type,
                            typename IO_type::Str_type
                                 >
                               >;
    /////////////////////////////////////////////////////////////////////////////////////
    template< class IO_type >
    class ini_file
    {
        //-------------------------------------------------------------------------------
        using Str_type = typename IO_type::Str_type;
        //-------------------------------------------------------------------------------
    public:
        //-------------------------------------------------------------------------------
        ini_file( const Str_type& file_name );
        //-------------------------------------------------------------------------------
        void                    load_from_file( const Str_type& file_name );
        //-------------------------------------------------------------------------------
        void                    save_file();
        //-------------------------------------------------------------------------------
        Str_type&            get( const Str_type& name_var );
        //-------------------------------------------------------------------------------
        const Str_type&      get( const Str_type& name_var ) const;
        //-------------------------------------------------------------------------------
        Str_type&     operator[]( const Str_type& name_var );
        //-------------------------------------------------------------------------------
        const Str_type& operator[]( const Str_type& name_var ) const;
        //-------------------------------------------------------------------------------
    private:
        //-------------------------------------------------------------------------------
        Str_type               file_name_;
        ini_map< IO_type >     map_file;
        static Str_type        err_;
    };
};
/////////////////////////////////////////////////////////////////////////////////////////
namespace tools
{
    //-----------------------------------------------------------------------------------
    template< class IO_type >
    using Str_type = typename IO_type::Str_type;
    //-----------------------------------------------------------------------------------
    template< class IO_type >
    typename IO_type::Str_type ini_file< IO_type >::err_ = "";
    //-----------------------------------------------------------------------------------
    template< class IO_type >
    ini_file< IO_type >::ini_file( const Str_type& file_name )
    {
        load_from_file( file_name );
        file_name_ = file_name;
    }
    //-----------------------------------------------------------------------------------
    template< class IO_type >
    void ini_file< IO_type >::load_from_file( const Str_type& file_name )
    {
        #define COMMENT_SYMBOL '#'
 
        typename IO_type::Input_file_type file( file_name );
        if  ( !file )
        {
            throw std::runtime_error( "Error open file" );
        }
        Str_type copy_str{};
 
        while( !file.eof() )
        {
            std::getline( file, copy_str );
            if  ( copy_str[0] == COMMENT_SYMBOL )
            {
                map_file.push_back( std::make_pair( copy_str, "" ) );
                continue;
            }
            if  ( copy_str.size() < 1 )
            {
                continue;
            }
            std::smatch match_var;
            std::regex_search( copy_str, match_var, std::regex( "(.*)=(.*)" ) );
            map_file.push_back( std::make_pair( match_var[1], match_var[2] ) );
        }
        file_name_ = file_name;
 
        #undef COMMENT_SYMBOL
    }
    //-----------------------------------------------------------------------------------
    template< class IO_type >
    void ini_file< IO_type >::save_file()
    {
        #define COMMENT_SYMBOL '#'
 
        typename IO_type::Output_file_type file( file_name_ );
        if  ( !file )
        {
            throw std::runtime_error( "Error open file" );
        }
 
        for(const auto& i : map_file )
        {
            if  ( i.first[0] == COMMENT_SYMBOL )
            {
                file << i.first << std::endl;
                continue;
            }
            file
                << i.first
                << "="
                << i.second
                << std::endl;
        }
 
        #undef COMMENT_SYMBOL
    }
    //-----------------------------------------------------------------------------------
    template< class IO_type >
    Str_type< IO_type >& ini_file< IO_type >::get( const Str_type& name_var )
    {
        auto find = [] (
                        const Str_type& find_var,
                        ini_map< IO_type >& map
                       )
                       -> Str_type&
        {
            for( auto& i : map )
            {
                if  ( i.first == find_var )
                {
                    return i.second;
                }
            }
            return ini_file::err_;
        };
        return find( name_var, map_file );
    }
    //-----------------------------------------------------------------------------------
    template< class IO_type >
    const Str_type< IO_type >& ini_file< IO_type >::get( const Str_type& name_var ) const
    {
        return get( name_var );
    }
    //-----------------------------------------------------------------------------------
    template< class IO_type >
    Str_type< IO_type >& ini_file< IO_type >::operator[] ( const Str_type& name_var )
    {
        return get( name_var );
    }
    //-----------------------------------------------------------------------------------
    template< class IO_type >
    const Str_type< IO_type >& ini_file< IO_type >::operator[] ( const Str_type& name_var ) const
    {
        return get( name_var );
    }
    //-----------------------------------------------------------------------------------
};

main.cpp
C++
1
2
3
4
5
6
#include "ini.hpp"
 
int main()
{
    tools::ini_file<tools::Std_IO> file;
}

Так же мне бы хотелось, чтобы мне подсказали, как мне уменьшить данный код. Просто где-то в глубине души я понимаю, что код этот очень большой, но уменьшить его можно, только я ещё пока не знаю -- как.
0
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
22.08.2016, 14:06
Ответы с готовыми решениями:

Шаблон родительского класса и шаблон класса потомка
Запутался, как правильно пронаследоваться от шаблона класса? #include &lt;iostream&gt; #include &lt;cmath&gt; using namespace std; ...

Шаблоны функций, Ошибка: для использования класса шаблон требуется список аргументов шаблон
Есть у меня 3 структуры Трамвай , Троллейбус , Автобус. Для автобуса определены функции (работают) Троллейбус и Трамвай одинаковые поля...

Шаблон класса, параметром которого должны являться наследники определённого класса
Сразу извиняюсь за нубский вопрос. Суть в том, что я хочу сделать шаблон класса, параметром которого должны являтся наследники...

24
19501 / 10106 / 2461
Регистрация: 30.01.2014
Сообщений: 17,825
22.08.2016, 18:26
Студворк — интернет-сервис помощи студентам
Цитата Сообщение от GbaLog- Посмотреть сообщение
Так-то с каждым днём понимаю, что такой стиль очень сложно поддерживать.
Самый главный недостаток, для которого не сработает позиция "о вкусах не спорят" - это полное отсутствие diff-friendly у такого форматирования. Во всех конторах используют системы контроля версий, и иногда приходится сводить изменения разных разработчиков. Так вот у такого форматирования зависимость символов не только горизонтальная, как обычно, но и вертикальная. Если у тебя три функции идут друг под другом, то они выравнены по началу своего имени, и если в результате рефакторинга добавилась функция с более длинным возвращаемым значением, то ты вынужден будешь сдвинуть все вышестоящие функции, чтобы сохранить форматирование. В итоге при просмотре diff у тебя получится изменений больше, чем реально было необходимо. И человек, который занимается сведением веток, я тебе клянусь, будет просто в ярости от такого.
Так что лучше отвыкать от этого пораньше.
2
Любитель чаепитий
 Аватар для GbaLog-
3745 / 1801 / 566
Регистрация: 24.08.2014
Сообщений: 6,020
Записей в блоге: 1
22.08.2016, 21:55  [ТС]
DrOffset, Если функций очень много, то можно просто "забить" на эту функцию и оставить её с одним пробелом между именем и return type'ом.

Добавлено через 3 часа 26 минут
В общем переписывал я класс, переписывал, и тут вылезла ошибка, над которой бьюсь уже около получаса, но понять, почему не работает, я так и не смог. В общем вот в этом моменте:
момент
C++
1
2
3
4
5
6
7
8
9
10
11
        using Str_type              = std::basic_string<Char_type>;
           std::match_results<Str_type::const_iterator> match_var;
            //std::match_results<std::string::const_iterator> match_var;
            
            if( !std::regex_search( copy_str, match_var, std::regex( "(.*)=(.*)" ) ) )
            {
                throw std::runtime_error( "Incorrect string in file" );
            }
//...
//main
tools::ini_file<char> file( "ololo.ini" );

вылетает ошибка, а именно в первой строке объявления std::match_results<>. Я не понимаю, в чём смысл, ведь второе компилируется без каких-либо проблем. Хотя по идее, первое должно разворачиваться во второе после прекомпилятора, не?
Вот полный код, он пока не доделан:
code
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
/////////////////////////////////////////////////////////////////////////////////////////
#include <regex>
#include <string>
#include <vector>
#include <utility>
#include <fstream>
#include <algorithm>
/////////////////////////////////////////////////////////////////////////////////////////
namespace tools
{
    /////////////////////////////////////////////////////////////////////////////////////
    template< class Char_type >
    class ini_file
    {
        //-------------------------------------------------------------------------------
        using Str_type              = std::basic_string<Char_type>;
        using File_type             = std::basic_fstream<Char_type>;
        using Input_file_type       = std::basic_ifstream<Char_type>;
        using Output_file_type      = std::basic_ofstream<Char_type>;
        using ini_map = std::vector< 
                                std::pair< 
                                            Str_type, 
                                            Str_type 
                                         > 
                                   >;
        //-------------------------------------------------------------------------------
        enum { e_comment = '#' };
        //-------------------------------------------------------------------------------
    public:
        //-------------------------------------------------------------------------------
        ini_file( const Str_type& file_name );
        //-------------------------------------------------------------------------------
        void                    load_from_file( const Str_type& file_name );
        //-------------------------------------------------------------------------------
        void                    save_file();
        //-------------------------------------------------------------------------------
        Str_type&               add( const Str_type& name_var, const Str_type& value );
        //-------------------------------------------------------------------------------
        Str_type&               get( const Str_type& name_var );
        //-------------------------------------------------------------------------------
        const Str_type&         get( const Str_type& name_var ) const;
        //-------------------------------------------------------------------------------
        Str_type&        operator[]( const Str_type& name_var );
        //-------------------------------------------------------------------------------
        const Str_type&  operator[]( const Str_type& name_var ) const;
        //-------------------------------------------------------------------------------
    private:
        //-------------------------------------------------------------------------------
        Str_type               file_name_;
        ini_map                map_file;
    };
};
/////////////////////////////////////////////////////////////////////////////////////////
namespace tools
{
    //-----------------------------------------------------------------------------------
    template< class Char_type >
    using Str_type = std::basic_string<Char_type>;
    //-----------------------------------------------------------------------------------
    template< class Char_type >
    ini_file< Char_type >::ini_file( const Str_type& file_name )
    {
        load_from_file( file_name );
        file_name_ = file_name;
    }
    //-----------------------------------------------------------------------------------
    template< typename Char_type >
    void ini_file< Char_type >::load_from_file( const Str_type& file_name )
    {
        Input_file_type file( file_name );
        if  ( !file )
        {
            throw std::runtime_error( "Error open file" );
        }
        Str_type copy_str{};
 
        while( !file.eof() )
        {
            std::getline( file, copy_str );
            if  ( copy_str[0] == e_comment )
            {
                map_file.push_back( std::make_pair( copy_str, "" ) );
                continue;
            }
            if  ( copy_str.size() < 1 )
            {
                continue;
            }
            
            std::match_results<Str_type::const_iterator> match_var;
            //std::match_results<std::string::const_iterator> match_var;
            
            if( !std::regex_search( copy_str, match_var, std::regex( "(.*)=(.*)" ) ) )
            {
                throw std::runtime_error( "Incorrect string in file" );
            }
            
            map_file.push_back( std::make_pair( match_var[1], match_var[2] ) );
        }
        file_name_ = file_name;
    }
    //-----------------------------------------------------------------------------------
    template< class Char_type >
    void ini_file< Char_type >::save_file()
    {
        Output_file_type file( file_name_ );
        if  ( !file )
        {
            throw std::runtime_error( "Error open file" );
        }
 
        for(const auto& i : map_file )
        {
            if  ( i.first[0] == e_comment )
            {
                file << i.first << std::endl;
                continue;
            }
            file
                << i.first
                << "="
                << i.second
                << std::endl;
        }
    }
    //-----------------------------------------------------------------------------------
    template< class Char_type >
    Str_type< Char_type >& ini_file< Char_type >::add( 
                                            const Str_type& name_var,
                                            const Str_type& value 
                                                )
    {
        map_file.push_back( std::make_pair( name_var, value ) );
        return map_file.at(map_file.size() - 1).second;
    }
    //-----------------------------------------------------------------------------------
    template< class Char_type >
    Str_type< Char_type >& ini_file< Char_type >::get( const Str_type& name_var )
    {
        
        auto iter = std::find_if( 
                            map_file.begin(), 
                            map_file.end(), 
                            [&name_var] (auto var)
                            {
                                return var.first == name_var;
                            }
                               );
        if  ( iter == map_file.end() )
        {
            return add( name_var, "" );
        }
        return *iter;
    }
    //-----------------------------------------------------------------------------------
    template< class Char_type >
    const Str_type< Char_type >& ini_file< Char_type >::get( const Str_type& name_var ) const
    {
        return get( name_var );
    }
    //-----------------------------------------------------------------------------------
    template< class Char_type >
    Str_type< Char_type >& ini_file< Char_type >::operator[] ( const Str_type& name_var )
    {
        return get( name_var );
    }
    //-----------------------------------------------------------------------------------
    template< class Char_type >
    const Str_type< Char_type >& ini_file< Char_type >::operator[] ( const Str_type& name_var ) const
    {
        return get( name_var );
    }
    //-----------------------------------------------------------------------------------
};
 
 
 
 
#include <iostream>
 
int main()
{
    std::cout << "Hello, world!\n";
    
    tools::ini_file<char> file( "ololo.ini" );
    
}

Так же этот ответ "призовет" в топик DrOffset, так как существует магия форума, о которой я знаю.
Так вот, вопрос к Вам, удалось ли мне спастись от UB или я до сих пор не понял, что Вы от меня хотели?
0
495 / 209 / 70
Регистрация: 27.05.2016
Сообщений: 557
22.08.2016, 23:23
GbaLog-,
C++
1
std::match_results<typename Str_type::const_iterator> match_var;
2
19501 / 10106 / 2461
Регистрация: 30.01.2014
Сообщений: 17,825
22.08.2016, 23:28
Цитата Сообщение от GbaLog- Посмотреть сообщение
Я не понимаю, в чём смысл
Смысл в зависимых именах шаблонов.
Надо так:
C++
1
std::match_results<typename Str_type::const_iterator> match_var;
Цитата Сообщение от GbaLog- Посмотреть сообщение
удалось ли мне спастись от UB или я до сих пор не понял, что Вы от меня хотели?
В целом да, понял. Удалось.
Осталась правда еще кое-что. Я бы на твоем месте условие if ( copy_str.size() < 1 ) перед if ( copy_str[0] == e_comment ) поставил, т.е. поменял бы их местами.
1
Любитель чаепитий
 Аватар для GbaLog-
3745 / 1801 / 566
Регистрация: 24.08.2014
Сообщений: 6,020
Записей в блоге: 1
23.08.2016, 11:39  [ТС]
DrOffset, А я ведь так делал, только rextester килял процесс после такого. Я не знаю, может проблема в rextester'e, но было именно так.
Сейчас он скушал.

Добавлено через 48 минут
В общем-то всё готово, и даже работает. Я скину сюда, вдруг кому-нибудь пригодится( хотя кого я обманываю ).
Кликните здесь для просмотра всего текста
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
/////////////////////////////////////////////////////////////////////////////////////////
#include <regex>
#include <string>
#include <vector>
#include <utility>
#include <fstream>
#include <algorithm>
/////////////////////////////////////////////////////////////////////////////////////////
namespace tools
{
    /////////////////////////////////////////////////////////////////////////////////////
    template< class Char_type >
    class ini_file
    {
        //-------------------------------------------------------------------------------
        using Str_type              = std::basic_string<Char_type>;
        using File_type             = std::basic_fstream<Char_type>;
        using Input_file_type       = std::basic_ifstream<Char_type>;
        using Output_file_type      = std::basic_ofstream<Char_type>;
        using ini_map = std::vector<
                                std::pair<
                                            Str_type,
                                            Str_type
                                         >
                                   >;
        //-------------------------------------------------------------------------------
        enum { e_comment = '#', e_equal = '=' };
        //-------------------------------------------------------------------------------
    public:
        //-------------------------------------------------------------------------------
        ini_file( const Str_type& file_name );
        //-------------------------------------------------------------------------------
        void                    load_from_file( const Str_type& file_name );
        //-------------------------------------------------------------------------------
        void                    save_file();
        //-------------------------------------------------------------------------------
        const Str_type&         add( const Str_type& name_var, const Str_type& value );
        //-------------------------------------------------------------------------------
        void                    set( const Str_type& name_var, const Str_type& value );
        //-------------------------------------------------------------------------------
        const Str_type&         get( const Str_type& name_var );
        //-------------------------------------------------------------------------------
        const Str_type&  operator[]( const Str_type& name_var );
        //-------------------------------------------------------------------------------
    private:
        //-------------------------------------------------------------------------------
        Str_type               file_name_;
        ini_map                map_file;
    };
};
/////////////////////////////////////////////////////////////////////////////////////////
namespace tools
{
    //-----------------------------------------------------------------------------------
    template< class Char_type >
    using Str_type = std::basic_string<Char_type>;
    //-----------------------------------------------------------------------------------
    template< class Char_type >
    ini_file< Char_type >::ini_file( const Str_type& file_name )
    {
        load_from_file( file_name );
        file_name_ = file_name;
    }
    //-----------------------------------------------------------------------------------
    template< class Char_type >
    void ini_file< Char_type >::load_from_file( const Str_type& file_name )
    {
        Input_file_type file( file_name );
        if  ( !file )
        {
            throw std::runtime_error( "Error open file" );
        }
        Str_type copy_str{};
 
        while( !file.eof() )
        {
            std::getline( file, copy_str );
            if  ( copy_str.size() < 1 )
            {
                continue;
            }
            if  ( copy_str[0] == e_comment )
            {
                map_file.push_back( std::make_pair( copy_str, "" ) );
                continue;
            }
 
            std::match_results<typename Str_type::const_iterator> match_var;
 
            if( !std::regex_search( copy_str, match_var, std::regex( "(.*)=(.*)" ) ) )
            {
                throw std::runtime_error( "Incorrect string in file" );
            }
 
            map_file.push_back( std::make_pair( match_var[1], match_var[2] ) );
        }
        file_name_ = file_name;
    }
    //-----------------------------------------------------------------------------------
    template< class Char_type >
    void ini_file< Char_type >::save_file()
    {
        Output_file_type file( file_name_ );
        if  ( !file )
        {
            throw std::runtime_error( "Error open file" );
        }
 
        for(const auto& i : map_file )
        {
            if  ( i.first[0] == e_comment )
            {
                file << i.first << std::endl;
                continue;
            }
            file
                << i.first
                << e_equal
                << i.second
                << std::endl;
        }
    }
    //-----------------------------------------------------------------------------------
    template< class Char_type >
    const Str_type< Char_type >& ini_file< Char_type >::add(
                                            const Str_type& name_var,
                                            const Str_type& value
                                                )
    {
        auto iter = std::find_if(
                                    map_file.begin(),
                                    map_file.end(),
                                    [&name_var] (auto var)
                                    {
                                        return var.first == name_var;
                                    }
                                );
        if( iter != map_file.end() )
        {
            throw std::runtime_error( "This name[" + name_var + "] already registered!" );
        }
        map_file.push_back( std::make_pair( name_var, value ) );
        return map_file.at(map_file.size() - 1).second;
    }
    //-----------------------------------------------------------------------------------
    template< class Char_type >
    void ini_file<Char_type>::set( const Str_type& name_var, const Str_type& value )
    {
        auto iter = std::find_if(
                                    map_file.begin(),
                                    map_file.end(),
                                    [&name_var] (auto var)
                                    {
                                        return var.first == name_var;
                                    }
                                );
        if( iter == map_file.end() )
        {
            add( name_var, value );
        }
        else
        {
            iter->second = value;
        }
    }
    //-----------------------------------------------------------------------------------
    template< class Char_type >
    const Str_type< Char_type >&
                        ini_file< Char_type >::get( const Str_type& name_var )
    {
 
        auto iter = std::find_if(
                                    map_file.begin(),
                                    map_file.end(),
                                    [&name_var] (auto var)
                                    {
                                        return var.first == name_var;
                                    }
                                );
        if  ( iter == map_file.end() )
        {
            return add( name_var, "" );
        }
        return iter->second;
    }
    //-----------------------------------------------------------------------------------
    template< class Char_type >
    const Str_type< Char_type >&
                    ini_file< Char_type >::operator[]( const Str_type& name_var )
    {
        return get( name_var );
    }
    //-----------------------------------------------------------------------------------
};
 
#include <iostream>
#include "ini.hpp"
 
int main()
{
    tools::ini_file<char> ini( "gba.ini" );
    std::cout << ini["test2dwa"] << std::endl;
    ini.set( "gbalog", "ololo" );
    std::cout << ini.get("gbalog") << std::endl;
    try
    {
        ini.add( "gbalog", "ya_zanyal_chye-to_mesto" );
    }
    catch(...)
    {
        std::cerr << "Error" << std::endl;
    }
    std::cout << ini["gbalog"] << std::endl;
}
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
23.08.2016, 11:39

Написать шаблон класса на основе класса vector для реализации стековой структуры данных
Пыталась написать код, но не уверена будет ли такая реализация корректной, можно ли это сделать как-то по - другому? И как надо...

Шаблон класса (параметризация класса)
Нужна помощь и советы!!! Англо-русский словарь построен как список. Каждая компонента содержит английское слово, соответствующее...

Создать шаблон некоторого класса, возможно, реализованного с применением некоторого серверного класса
Добрый день, Уважаемые профессионалы. Прошу помочь в решении задачи. Честно говоря, я ничего не понимаю. И вот...решил...

Шаблон класса
Привет всем! Решил написать программу с шаблонами. Вот 3 файла: //tree.h #pragma once template &lt;class T&gt; ...

Шаблон класса
Приветствую. Есть глупый вопрос. Имеется класс: #pragma once #include &quot;support.hpp&quot; template &lt;typename at&gt; class...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
25
Ответ Создать тему
Новые блоги и статьи
сукцессия 12. краткий список проверок модели перед запуском.
anaschu 27.06.2026
Скрытые отказы в моделях систем динамики (SD-models) экологических систем: два случая из практики Контекст Разбирался прототип модели систем динамики (SD-модели) микоризной сукцессии: пять. . .
Сукцессия 11. Проверка орудий перед войной: разработка через тестирование
anaschu 27.06.2026
Как не дать модели соврать самой себе: проверки для симуляции микоризной сукцессии Введение Когда вы строите математическую модель живой системы — грибов, растений, почвы — главная опасность. . .
10 сукцессия. Питон код войны грибов и растений
anaschu 27.06.2026
import numpy as np class PlantAgent: def __init__(self, name, strategy, initial_biomass): self. name = name self. strategy = strategy # "greedy" (широколиственные) или. . .
сукцессия 9. Математика подлости: как растения предали грибных друзей
anaschu 27.06.2026
Статья 2. Глобальная фосфорная война: эволюционно-экономические механизмы распределения биомов Земли Введение: Экологический рынок как игра с нулевой суммой Традиционная экология долгое время. . .
сукцессия 8. Как я спорил с ИИ, которые - агенты растений и ненавистники грибов!
anaschu 27.06.2026
Статья 1. Хроники грибного восстания: как Сократов диалог разрушил академические догмы ИИ Введение: Синдром «цифрового учебника» Современные большие языковые модели (LLM) обладают колоссальным. . .
Главный вопрос моделирования сукцессии
anaschu 27.06.2026
главный вопрос. Если эктомикориза лучше добывает недоступный фосфор. И ее масса максимальна из всех. А широколиственный лес тоже имеет самую крутую биомассу. То почему не возникло их симбиоза? Это. . .
сукцессия 6. Питон реализация энилоджиковской модели, картинка про Центральную часть будущей модели
anaschu 26.06.2026
Етить. ИИ мне на основе моего старого файла R создал вот эту вот хмерь на пайтоне. Это уже новая модель, модель сукцессии грибной. потоки фосфора, азота. Углерода. 5 видов организмов. Я даже. . .
Как замкнутый ядерный цикл решит проблему недостатки фосфора? Био миграция фосфора со дна океана
anaschu 26.06.2026
Биологический лифт: Концепция подъема фосфора со дна океана с помощью ЗЯТЦ Предлагаю на обсуждение альтернативу тяжелому промышленному бурению океанического дна. Вместо сложной инженерии мы можем. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru