Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.50/4: Рейтинг темы: голосов - 4, средняя оценка - 4.50
Эксперт С++
 Аватар для Avazart
8484 / 6151 / 615
Регистрация: 10.12.2010
Сообщений: 28,683
Записей в блоге: 30

E2199 QUESTIONABLE!!! Template friend function must be previously declared

05.10.2016, 23:24. Показов 865. Ответов 8

Студворк — интернет-сервис помощи студентам
Есть такой минимальный код:
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
#include <string>
 
template<typename CharT>
class Format
{
public:
  typedef std::basic_string<CharT> StringT;
 
  template< typename CharT>
  friend Format<CharT> format(const std::basic_string<CharT>& str,std::size_t n);
 
  template< typename CharT>
  friend Format<CharT> format(const CharT* str,std::size_t n);
  
private:
  Format(const StringT& str, std::size_t firstArgNumber=0){};
  Format(const Format& f){};
  Format& operator==(const Format& f){};
};
//----------------------- friend format() -----------------------------------------
template< typename CharT>
Format<CharT> format(const std::basic_string<CharT>& str,std::size_t n=0)
{
  return Format<CharT>(str,n);
}
//---------------------------------------------------------------------------------
template< typename CharT>
Format<CharT> format(const CharT* c_str,std::size_t n=0)
{
  return Format<CharT>(c_str,n);
}
//---------------------------------------------------------------------------------
 
int main()
{
  using namespace std;
 
  format("some");
  
  return 0;
}
В MSVC2010 компилится, в C++BuilderXE3 и на http://ideone.com/JpT4na не хочет:

Цитата Сообщение от C++BuilderXE3
[bcc32 Error] Format.h(97): E2199 QUESTIONABLE!!! Template friend function 'Format<CharT>(const basic_string<CharT,char_traits<CharT>,al locator<CharT> > &,unsigned int)' must be previously declared
И
Цитата Сообщение от ideone
в prog.cpp:9:13: error: declaration of 'class CharT'
template< typename CharT>
^
prog.cpp:3:10: error: shadows template parm 'class CharT'
template<typename CharT>
^
prog.cpp:12:13: error: declaration of 'class CharT'
Смысл закрыть от вне конструкторы и оператор присвоения, разрешить создавать Format только через friend ф-цию и его методы.
Как правильно записать?

0
IT_Exp
Эксперт
34794 / 4073 / 2104
Регистрация: 17.06.2006
Сообщений: 32,602
Блог
05.10.2016, 23:24
Ответы с готовыми решениями:

C:\Dev-Cpp\lib\vector.h `ostream' is neither function nor member function; cannot be declared friend
выкидывает C:\Dev-Cpp\lib\vector.h `ostream' is neither function nor member function; cannot be declared friend при компиляции. что делать?

Selfpointer inside template friend function
Как получить указатель на нужный класс внутри дружественной фукции? def.h class A { public: template...

Ошибка: friend declaration declares a non-template function
Всем доброго времени суток! Я корплю над задачкой: нада сделать класс вектор шаблонным, перегрузить операции ввода-вывода, и тд и тп. ...

8
Эксперт С++
 Аватар для hoggy
8973 / 4319 / 960
Регистрация: 15.11.2014
Сообщений: 9,760
05.10.2016, 23:29
Цитата Сообщение от Avazart Посмотреть сообщение
Как правильно записать?
http://ideone.com/N1jaQQ
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
#include <string>
 
template<typename CharT>
class Format
{
public:
  typedef std::basic_string<CharT> StringT;
 
  template< typename CharU>
  friend Format<CharU> format(const std::basic_string<CharU>& str,std::size_t n);
 
  template< typename CharU>
  friend Format<CharU> format(const CharU* str,std::size_t n);
  
private:
  Format(const StringT& str, std::size_t firstArgNumber=0){};
  Format(const Format& f){};
  Format& operator==(const Format& f){};
};
//----------------------- friend format() -----------------------------------------
template< typename CharT>
Format<CharT> format(const std::basic_string<CharT>& str,std::size_t n=0)
{
  return Format<CharT>(str,n);
}
//---------------------------------------------------------------------------------
template< typename CharT>
Format<CharT> format(const CharT* c_str,std::size_t n=0)
{
  return Format<CharT>(c_str,n);
}
//---------------------------------------------------------------------------------
 
int main()
{
  using namespace std;
  
  
  format("some");
  
  return 0;
}
2
Эксперт С++
 Аватар для Avazart
8484 / 6151 / 615
Регистрация: 10.12.2010
Сообщений: 28,683
Записей в блоге: 30
05.10.2016, 23:35  [ТС]
hoggy, Спасибо... Но C++Builder все равно не хочет:
[bcc32 Error] Format.h(97): E2199 QUESTIONABLE!!! Template friend function 'Format<CharU>(const basic_string<CharU,char_traits<CharU>,al locator<CharU> > &,unsigned int)' must be previously declared
Что ему не нравится непонятно...
0
19491 / 10097 / 2460
Регистрация: 30.01.2014
Сообщений: 17,805
05.10.2016, 23:39
Цитата Сообщение от Avazart Посмотреть сообщение
must be previously declared
Ну дай ему что он хочет
Только с параметрами по-умолчанию определись. Они должны быть в объявлении функции.

Добавлено через 2 минуты
Кликните здесь для просмотра всего текста
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
template<typename CharT>
class Format;
 
template< typename CharT>
Format<CharT> format(const std::basic_string<CharT>& str,std::size_t n=0);
 
template< typename CharT>
Format<CharT> format(const CharT* c_str,std::size_t n=0);
 
template<typename CharT>
class Format
{
public:
  typedef std::basic_string<CharT> StringT;
 
  template< typename CharU>
  friend Format<CharU> format(const std::basic_string<CharU>& str,std::size_t n);
 
  template< typename CharU>
  friend Format<CharU> format(const CharU* str,std::size_t n);
  
private:
  Format(const StringT& str, std::size_t firstArgNumber=0){};
  Format(const Format& f){};
  Format& operator==(const Format& f){};
};
//----------------------- friend format() -----------------------------------------
template< typename CharT>
Format<CharT> format(const std::basic_string<CharT>& str,std::size_t n)
{
  return Format<CharT>(str,n);
}
//---------------------------------------------------------------------------------
template< typename CharT>
Format<CharT> format(const CharT* c_str,std::size_t n)
{
  return Format<CharT>(c_str,n);
}
//---------------------------------------------------------------------------------
 
int main()
{
  using namespace std;
  
  format("some");
  
  return 0;
}
2
Эксперт С++
 Аватар для Avazart
8484 / 6151 / 615
Регистрация: 10.12.2010
Сообщений: 28,683
Записей в блоге: 30
05.10.2016, 23:53  [ТС]
Цитата Сообщение от DrOffset Посмотреть сообщение
Ну дай ему что он хочет
Только с параметрами по-умолчанию определись. Они должны быть в объявлении функции.
Я только что попробовал, не канает:
[bcc32 Error] File1.cpp(44): E2247 'Format<char>::Format(const std::string &,unsigned int)' is not accessible
[bcc32 Error] File1.cpp(44): E2247 'Format<char>::Format(const Format<char> &)' is not accessible
Добавлено через 10 минут
Даже так:
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
#include <string>
 
template<typename CharT>
class Format;
 
template< typename CharT>
Format<CharT> format(const std::basic_string<CharT>& str,std::size_t n);
 
//template< typename CharT>
//Format<CharT> format(const CharT* c_str,std::size_t n);
 
template<typename CharT>
class Format
{
public:
    typedef std::basic_string<CharT> StringT;
 
    template<typename CharU>
    friend Format<CharU> format(const std::basic_string<CharU>& str,std::size_t n)
    {
        return Format<CharU>(str,n);
    }
 
//  template< typename CharU>
//  friend Format<CharU> format(const CharU* str,std::size_t n)
//  {
//      return Format<CharU>(c_str,n);
//  }
 
private:
    Format(const StringT& str, std::size_t firstArgNumber=0){};
    Format(const Format& f){};
    Format& operator==(const Format& f){};
};
//---------------------------------------------------------------------------------
 
int main()
{
    using namespace std;
 
    string s("some");
 
    format(s,0);
 
    return 0;
}
Не хочет:
[bcc32 Error] File1.cpp(48): E2034 Cannot convert 'string' to 'basic_string<CharU,char_traits<CharU>,a llocator<CharU> >'
[bcc32 Error] File1.cpp(48): E2342 Type mismatch in parameter 'str' (wanted 'const basic_string<CharU,char_traits<CharU>,al locator<CharU> > &', got 'string')
0
19491 / 10097 / 2460
Регистрация: 30.01.2014
Сообщений: 17,805
06.10.2016, 00:17
Цитата Сообщение от Avazart Посмотреть сообщение
Не хочет:
Ну что-то компилятор мозги нам пудрит.
Видимо нужно придумать какой-то workaround, который обойдет эти его баги. Будет время завтра, подумаю.
Сегодня уже все.
0
Эксперт С++
 Аватар для Avazart
8484 / 6151 / 615
Регистрация: 10.12.2010
Сообщений: 28,683
Записей в блоге: 30
06.10.2016, 09:51  [ТС]
Да видимо просто придется оставить открытыми конструкторы и оператор присвоения.
Я хотел сделать следующее:
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int main()
{
  using namespace std;
  using namespace Bicycle;
 
  string s1= format("%0, %1, %2, %0")% "s" % 15 % 20.667;
  string s2=
      format("%0, %1, %2, %0").arg("s")
                              .arg(15,0,16) // hex
                              .arg(20.667,10,'s',2,'0'); //scientific
 
 
 
  cout<<s1<<endl<<s2<<endl;
  getchar();
  return 0;
}
s, 15, 20.667, s
s, f, 02.07e+001, s

Как мне показалось в данном случае, создание Format вручную нежелательно.
0
2549 / 1208 / 358
Регистрация: 30.11.2013
Сообщений: 3,826
06.10.2016, 10:04
Вот кстати тоже тема с проблемой шаблонного friend Friend declaration construction - Nosey, разбирается - может он и вам поможет)))
1
Эксперт С++
 Аватар для Avazart
8484 / 6151 / 615
Регистрация: 10.12.2010
Сообщений: 28,683
Записей в блоге: 30
06.10.2016, 10:49  [ТС]
rikimaru2013, Да действительно помогло.
Вот так работает:

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
#include <iostream>
 
#include <string>
 
template<typename CharT>
class Format;
 
template< typename CharT>
Format<CharT> format(const std::basic_string<CharT>& str,std::size_t n=0);
 
template< typename CharT>
Format<CharT> format(const CharT* str,std::size_t n=0);
 
template<typename CharT>
class Format
{
public:
    typedef std::basic_string<CharT> StringT;
 
    friend Format format<CharT>(const StringT& str,std::size_t n);
    friend Format format<CharT>(const CharT* str,std::size_t n);
 
private:
    Format(const StringT& str, std::size_t firstArgNumber=0){};
    Format(const Format& f){};
    Format& operator==(const Format& f){};
};
//----------------------- friend format() -----------------------------------------
template< typename CharT>
Format<CharT> format(const std::basic_string<CharT>& str,std::size_t n)
{
    return Format<CharT>(str,n);
}
//---------------------------------------------------------------------------------
template< typename CharT>
Format<CharT> format(const CharT* c_str,std::size_t n)
{
    return Format<CharT>(c_str,n);
}
//---------------------------------------------------------------------------------
 
int main()
{
    using namespace std;
 
    format(L"some");
 
    getchar();
  return 0;
}
1
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
BasicMan
Эксперт
29316 / 5623 / 2384
Регистрация: 17.02.2009
Сообщений: 30,364
Блог
06.10.2016, 10:49
Помогаю со студенческими работами здесь

Cannot redeclare db_connect() (previously declared
Cannot redeclare db_connect() (previously declared in Z:\home\shop\www\db_fns.php:3) in Z:\home\shop\www\db_fns.php on line 16 ...

Не работает скрипт, ошибка Cannot redeclare test() (previously declared
1.Задание Создайте анонимную функцию и поместите её в переменную. Функция должна просто возвращать сумму двух переданных параметров. ...

Ошибка: E;Test_Goal, pos: 321, 103 This domain was declared previously file
Задание:Найти в тексте слова-перевертыши из трех и более символов. Написал программу,и вылезла такая ошибка: E;Test_Goal, pos: 321, 103...

Error: 'stCircle' declared as function returning a function
Собственно говоря есть код и в 17 строке, почему то, компилятор выдает ошибку следующего содержания: &quot;\main.cpp|17|error: 'stCircle'...

Friend template class with template class argument
Помогите подружить 2 класса: Имеется класс Student: template &lt;class _T&gt; class Faculty; class Student{ friend...


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

Или воспользуйтесь поиском по форуму:
9
Ответ Создать тему
Новые блоги и статьи
моя боль
iceja 24.01.2026
Выложила интерполяцию кубическими сплайнами www. iceja. net REST сервисы временно не работают, только через Web. Написала за 56 рабочих часов этот сайт с нуля. При помощи perplexity. ai PRO , при. . .
Модель сукцессии микоризы
anaschu 24.01.2026
Решили писать научную статью с неким РОманом
http://iceja.net/ математические сервисы
iceja 20.01.2026
Обновила свой сайт http:/ / iceja. net/ , приделала Fast Fourier Transform экстраполяцию сигналов. Однако предсказывает далеко не каждый сигнал (см ограничения http:/ / iceja. net/ fourier/ docs ). Также. . .
http://iceja.net/ сервер решения полиномов
iceja 18.01.2026
Выкатила http:/ / iceja. net/ сервер решения полиномов (находит действительные корни полиномов методом Штурма). На сайте документация по API, но скажу прямо VPS слабенький и 200 000 полиномов. . .
Расчёт переходных процессов в цепи постоянного тока
igorrr37 16.01.2026
/ * Дана цепь(не выше 3-го порядка) постоянного тока с элементами R, L, C, k(ключ), U, E, J. Программа находит переходные токи и напряжения на элементах схемы классическим методом(1 и 2 з-ны. . .
Восстановить юзерскрипты Greasemonkey из бэкапа браузера
damix 15.01.2026
Если восстановить из бэкапа профиль Firefox после переустановки винды, то список юзерскриптов в Greasemonkey будет пустым. Но восстановить их можно так. Для этого понадобится консольная утилита. . .
Сукцессия микоризы: основная теория в виде двух уравнений.
anaschu 11.01.2026
https:/ / rutube. ru/ video/ 7a537f578d808e67a3c6fd818a44a5c4/
WordPad для Windows 11
Jel 10.01.2026
WordPad для Windows 11 — это приложение, которое восстанавливает классический текстовый редактор WordPad в операционной системе Windows 11. После того как Microsoft исключила WordPad из. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru