Battle_Hamster 1 / 1 / 1 Регистрация: 27.12.2013 Сообщений: 94 |
||||
1 |
||||
27.05.2014, 00:02. Показов 7657. Ответов 7 Метки нет (Все метки)
Приветствую! собсно код: ошибка — 20 строка
текст ошибок: D:uniwersityInzeneria Oprogramowaniaproekt_zaliczeniowycppQT_projekt uczelniaTWyklad.h:20: ошибка: ‘TStudent’ was not declared in this scope
__________________
0 |
5493 / 4888 / 831 Регистрация: 04.06.2011 Сообщений: 13,587 |
|
27.05.2014, 00:31 |
2 |
Что в файле TStudent.h?
0 |
Battle_Hamster 1 / 1 / 1 Регистрация: 27.12.2013 Сообщений: 94 |
||||
27.05.2014, 00:44 [ТС] |
3 |
|||
alsav22,
0 |
alsav22 5493 / 4888 / 831 Регистрация: 04.06.2011 Сообщений: 13,587 |
||||||||
27.05.2014, 00:52 |
4 |
|||||||
РешениеПопробуйте так:
1 |
Battle_Hamster 1 / 1 / 1 Регистрация: 27.12.2013 Сообщений: 94 |
||||
27.05.2014, 00:58 [ТС] |
5 |
|||
alsav22, а можно глупый вопрос?
0 |
5493 / 4888 / 831 Регистрация: 04.06.2011 Сообщений: 13,587 |
|
27.05.2014, 01:04 |
6 |
Программа потом будет правильно находить пути к классам? Будет.
И почему такой метод помог, а добавление заголовочных файлов — нет? У вас, в TStudent.h и в TWyklad.h взаимное включение, из-за этого ошибка. Если в хедере только указатели на класс, то достаточно форвард-объяления класса (без инклуда хедера с классом).
Спрашиваю, потому что есть ещё один класс, использующий вектор TStudent, и там при добавлении заголовочного ошибки не было, А тут взаимного включения нет (в TStudent.h нет инклуда TUczlenia.h).
1 |
Battle_Hamster 1 / 1 / 1 Регистрация: 27.12.2013 Сообщений: 94 |
||||||||||||
27.05.2014, 01:35 [ТС] |
7 |
|||||||||||
alsav22, в Wyklad.h есть декларация вектора:
а в Wyklad.cpp компилятор ругается, что такого вектора не существует:
ошибка: Добавлено через 1 минуту
Добавлено через 21 минуту
0 |
1 / 1 / 1 Регистрация: 27.12.2013 Сообщений: 94 |
|
27.05.2014, 01:39 [ТС] |
8 |
alsav22, Спасибо Вам за помощь
0 |
- Forum
- Beginners
- Template argument invalid — Trying to us
Template argument invalid — Trying to use it as a vector type
I’m getting a stupid little error and I’m pretty lost to where I’m going wrong.
When I try to compile my code it says: Template argument 1 is invalid
Template argument 2 is invalid
Refering to the «type» template I declared.
Am I declaring it wrong or am I just totally blind and missing something obvious?
Because if I just change the «type» template that I made with, say, int,
it works fine.
|
|
Last edited on
displayvector is also a templated function (it uses «type»).
And templates need to be fully visible (including their implementation) at the point of use since they are instantiated at compile time.
|
|
Last edited on
Ooooh I see, I got it now
So does that make the functions inline in this case?
Thanks again tpb
Last edited on
The actual functions generated from the templates will not necessarily be inlined. It’s just that the source text needs to be visible at compile time to generate the actual function(s) requested. There are whole C++ libraries that are header only because they consist only of templates. Most of boost is just headers. https://www.boost.org/
Got you man. Thank you once again!..
Topic archived. No new replies allowed.
Hello. I faced such a problem that the working program does not compile in Qt 6.2.
C:Program1apsabuilddebugindicationmoc_qcustomplot.cpp:249: error: template argument 1 is invalid
….builddebugindicationmoc_qcustomplot.cpp:249:54: error: template argument 1 is invalid
, QtPrivate::TypeAndForceComplete<QCP, std::true_type>
^
Please tell me when full support will appear?
https://ibb.co/K7YFTtS
https://ibb.co/SmbH9wd
Qt6.2 isn’t released yet, so I guess not until then
why this error?
Qt 5.15
249 | , QtPrivate::TypeAndForceComplete<QCP, std::true_type>
I am facing the same problem. It does not compile with Qt 6.2
Same here… I don’t know how to fix it… help!!!
The same problem has appeared. Is there any solution?
I have faced the same problem. Please help!
HI there,
I’m facing the exact same issue. Anyone solved this issue ?
thank you very much for your help.
Olivier
Same issue on 6.0.2
debugmoc_qcustomplot.cpp:249:54: error: template argument 1 is invalid
249 | , QtPrivate::TypeAndForceComplete<QCP, std::true_type>
| ^
debugmoc_qcustomplot.cpp:248:1: error: template argument 2 is invalid
248 | qt_incomplete_metaTypeArray<qt_meta_stringdata_QCP_t
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
249 | , QtPrivate::TypeAndForceComplete<QCP, std::true_type>
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Hi, same issue on 6.2.2. Did anyone found the solution?
Hi guys,I have the same problem
Qt version 6.2.3
When i update to QtPrivate::TypeAndForceComplete<int, std::true_type>, compile pass
————————————-
I didn’t find a template for it
qt_incomplete_metaTypeArray<qt_meta_stringdata_Object_t
, QtPrivate::TypeAndForceComplete<int, std::true_type>, QtPrivate::TypeAndForceComplete<int, std::true_type>, QtPrivate::TypeAndForceComplete<void, std::false_type>, QtPrivate::TypeAndForceComplete<int, std::false_type>, QtPrivate::TypeAndForceComplete<void, std::false_type>, QtPrivate::TypeAndForceComplete<int, std::false_type>
, QtPrivate::TypeAndForceComplete<void, std::false_type>, QtPrivate::TypeAndForceComplete<int, std::false_type>, QtPrivate::TypeAndForceComplete<void, std::false_type>, QtPrivate::TypeAndForceComplete<int, std::false_type>
, QtPrivate::TypeAndForceComplete<int, std::false_type>, QtPrivate::TypeAndForceComplete<void, std::false_type>, QtPrivate::TypeAndForceComplete<const int &, std::false_type>, QtPrivate::TypeAndForceComplete<int, std::false_type>, QtPrivate::TypeAndForceComplete<void, std::false_type>, QtPrivate::TypeAndForceComplete<const int &, std::false_type>
, QtPrivate::TypeAndForceComplete<QString, std::false_type>, QtPrivate::TypeAndForceComplete<QObject *, std::false_type>, QtPrivate::TypeAndForceComplete<QString, std::false_type>
>,
——————————-
It’s supposed to be a temporary fix
If you compile successfully, please give me a thumbs up
I changed these lines in qcustomplot.h
#ifndef Q_MOC_RUN
namespace QCP {
#else
class QCP { // when in moc-run, make it look like a class, so we get Q_GADGET, Q_ENUMS/Q_FLAGS features in namespace
Q_GADGET
Q_ENUMS(ExportPen)
Q_ENUMS(ResolutionUnit)
Q_ENUMS(SignDomain)
Q_ENUMS(MarginSide)
Q_FLAGS(MarginSides)
Q_ENUMS(AntialiasedElement)
Q_FLAGS(AntialiasedElements)
Q_ENUMS(PlottingHint)
Q_FLAGS(PlottingHints)
Q_ENUMS(Interaction)
Q_FLAGS(Interactions)
Q_ENUMS(SelectionRectMode)
Q_ENUMS(SelectionType)
public:
#endif
to this
namespace QCP {
Thank you colzlor ! it worked. You are the best.
FYI, QCP 2.1.1 establishes compatibility up to Qt6.4;
Thanks for the discussions here!
Добрый вечер, я пытаюсь создать шаблонный класс, в котором два члена, которые являются const_iterators, указывают на начало и конец подраздела вектора. Я хотел сделать класс универсальным, чтобы я мог использовать его для вектора любого типа.
Мои определения классов находятся в файле ThreadWorker.h и выглядят следующим образом:
template <typename T>
class VectorWorker
{
public:
VectorWorker<T>() = default;
VectorWorker<T>( std::vector<typename T>::const_iterator begin, std::vector<typename T>::const_iterator end);
void Work() const;
private:
std::vector<typename T>::const_iterator beginIt; /* Stores value of left iterator that defines data for this worker */
std::vector<typename T>::const_iterator endIt; /* Stores value of right iterator that defines data for this worker */
};
Когда я пытаюсь скомпилировать свой код, я получаю сообщение об ошибке, указывающее, что аргументы шаблона недопустимы:
error: template argument 1 is invalid
VectorWorker<T>( std::vector<typename T>::const_iterator begin, std::vector<typename T>::const_iterator end);
Я не совсем понимаю, почему я получаю эту ошибку, так как я указал через ключевое слово «typename», что T является параметром шаблона typename. Может ли кто-нибудь помочь объяснить, что здесь происходит, или указать мне хороший ресурс? Благодарю.
1
Решение
Попробуйте переместить typename
за пределами template
список аргументов:
template<typename T>
class VectorWorker {
private:
typename std::vector<T>::const_iterator beginIt;
typename std::vector<T>::const_iterator endIt;
public:
VectorWorker<T>() = default;
VectorWorker<T>( typename std::vector<T>::const_iterator begin, typename std::vector<T>::const_iterator end ) :
beginIt( begin ),
endIt( end )
{}
};
То, что вы ранее имели как члены и параметры конструктора
std::vector<typename T>::const_iterator beginIt; std::vector<typename T>::const_iterator endIt; std::vector<typename T>::const_iterator begin; std::vector<typename T>::const_iterator end;
Не Types
Для разрешения этого списка параметров шаблона для членов, а также параметров конструктора нужен только тип шаблона <T>
Чтобы сделать const_iterator
Это тип, который вы должны объявить как typename
typename std::vector<T>::const_iterator name;
1
Другие решения
Других решений пока нет …
Recommended Answers
When templatizing a class, you need to use a template statement before the class definition. Additionally, a matching template statement should preceed each function implementation that is not part of the class’s definition. You only need the Template Parameter on the class name, not the function name. This:
Jump to Post
hi !
![]()
how can we instanciate the constructor in main() using «new» ?You don’t «instantiate the constructor» you instantiate the class. When you perform the instantiation, the appropriate constructor gets called as part of the instantiation process.
Jump to Post
All 6 Replies
Fbody
682
Posting Maven
Featured Poster
12 Years Ago
When templatizing a class, you need to use a template statement before the class definition. Additionally, a matching template statement should preceed each function implementation that is not part of the class’s definition. You only need the Template Parameter on the class name, not the function name. This:
Vector<T>::Vector<T>() :capacity(0), size(0) {} //this is the line I am having problems with.
Should be this:
template <class T>
Vector<T>::Vector() :capacity(0), size(0) {} //this is the line I am having problems with.
You also need to put the function’s return type and/or qualifiers (such as «explicit») before the class resolution, not after.
template <class T>
explicit Vector<T>::Vector( int num ) {
//to be implemented.
//
}
An example:
//declare a templatized class
template <class T>
class TempClass {
public:
TempClass(); //default constructor
T memberFunc(T); //another member
}; //end class definition
//implement default constructor
template <class T>
TempClass<T>::TempClass() {}
//implement TempClass<T>::memberFunc()
template <class T>
T TempClass<T>::memberFunc(T someNewT) {
T anotherNewT;
/* do something */
return anotherNewT;
}
Edited
12 Years Ago
by Fbody because:
n/a
12 Years Ago
hi !
how can we instanciate the constructor in main() using «new» ?
12 Years Ago
hi !
in this case ,how can we instanciate the constructor in main() using «new» ?
12 Years Ago
I THINK it works like this because new returns a pointer to the object. So I just declare a pointer to the object of that type and then give it the address new returns.
TempClass<int> *tv = new TempClass<int>;
12 Years Ago
I used this in SystemC implementation
it work !! thank you Dazaa :icon_wink:
Fbody
682
Posting Maven
Featured Poster
12 Years Ago
hi !
![]()
how can we instanciate the constructor in main() using «new» ?
You don’t «instantiate the constructor» you instantiate the class. When you perform the instantiation, the appropriate constructor gets called as part of the instantiation process.
Reply to this topic
Be a part of the DaniWeb community
We’re a friendly, industry-focused community of developers, IT pros, digital marketers,
and technology enthusiasts meeting, networking, learning, and sharing knowledge.
Здравствуйте! Я пытают подключить библиотеку QCustomPlot в Qt Creator, но при запуске выдает ошибку template argument 1 is invalid. В интернете я нашел тему, где объясняют, как исправить эту ошибку, но там эта проблема возникала для пользовательского кода и исправлялась просто тем, что убрали один из инклудов, но у меня эта проблема возникла с библиотечным файлом, поэтому я не знаю, что делать. Как вообще могут возникать ошибки в подобных библиотеках?
Цитата
Topic starter
Размещено : 30.01.2022 22:07
Если я правильно понял, то ошибка была в библиотеке. Я скачал более раннюю версию библиотеки QCustomPlot 2.0.0 (2017, а была 2021 года) и выбрал более старую версию компилятора, и у меня все запустилось. 😀
ОтветитьЦитата
Topic starter
Размещено : 31.01.2022 00:45
@rodion-2 отлично! 🙂
ОтветитьЦитата
Размещено : 31.01.2022 09:38