Error template argument 1 is invalid

Ошибка "template argument 1 is invalid" C++ Решение и ответ на вопрос 1189369

Battle_Hamster

1 / 1 / 1

Регистрация: 27.12.2013

Сообщений: 94

1

27.05.2014, 00:02. Показов 7657. Ответов 7

Метки нет (Все метки)


Приветствую!
Слабое знание английского не помогло мне найти ответа на stackoverflow, поэтому надеюсь, что кто-нибудь может помочь

собсно код:

ошибка — 20 строка

C++ (Qt)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#if !defined(_TWYKLAD_H)
#define _TWYKLAD_H
 
#include <iostream>
#include<vector>
#include<TStudent.h>
using namespace std;
 
class TWyklad {
public:
    TWyklad(string nazwa, int idWykladu);
    void setNazwa(string nazwa);
    string getNazwa();
    void setIdWykladu(int idWykladu);
    int getIdWykladu();
private:
    string nazwa;
    int idWykladu;
    std::vector <TStudent*> studenci1;// powiazanie
};
 
#endif  //_TWYKLAD_H

текст ошибок:

D:uniwersityInzeneria Oprogramowaniaproekt_zaliczeniowycppQT_projekt uczelniaTWyklad.h:20: ошибка: ‘TStudent’ was not declared in this scope
std::vector <TStudent*> studenci1;// powiazanie
^
D:uniwersityInzeneria Oprogramowaniaproekt_zaliczeniowycppQT_projekt uczelniaTWyklad.h:20: ошибка: template argument 1 is invalid
std::vector <TStudent*> studenci1;// powiazanie
^
D:uniwersityInzeneria Oprogramowaniaproekt_zaliczeniowycppQT_projekt uczelniaTWyklad.h:20: ошибка: template argument 2 is invalid

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



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,

C++ (Qt)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#if !defined(_TSTUDENT_H)
#define _TSTUDENT_H
#include <iostream>
#include<vector>
#include<TWyklad.h>
using namespace std;
 
class TStudent {
public:
    TStudent(string nazwisko, int idStudenta);
    void setName(string nazwisko);
    string getName();
    void zapiszNaWyklad(TWyklad *newWyklad);
    const TWyklad* odzczytajWyklad(int id) const;
private:
    //  
    string nazwisko;
    int idStudenta;
   std::vector <TWyklad*> wyklady; // powiazanie
 
};
 
#endif  //_TSTUDENT_H



0



alsav22

5493 / 4888 / 831

Регистрация: 04.06.2011

Сообщений: 13,587

27.05.2014, 00:52

4

Лучший ответ Сообщение было отмечено Battle_Hamster как решение

Решение

Попробуйте так:

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#if !defined(_TWYKLAD_H)
#define _TWYKLAD_H
#include <iostream>
#include<vector>
//#include<TStudent.h>
using namespace std;
 
class TStudent;
 
class TWyklad {
public:
    TWyklad(string nazwa, int idWykladu);
    void setNazwa(string nazwa);
    string getNazwa();
    void setIdWykladu(int idWykladu);
    int getIdWykladu();
private:
    string nazwa;
    int idWykladu;
    std::vector <TStudent*> studenci1;// powiazanie
};
 
#endif  //_TWYKLAD_H
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
#if !defined(_TSTUDENT_H)
#define _TSTUDENT_H
#include <iostream>
#include<vector>
//#include<TWyklad.h>
using namespace std;
 
class TWyklad;
 
class TStudent {
public:
    TStudent(string nazwisko, int idStudenta);
    void setName(string nazwisko);
    string getName();
    void zapiszNaWyklad(TWyklad *newWyklad);
    const TWyklad* odzczytajWyklad(int id) const;
private:
    //  
    string nazwisko;
    int idStudenta;
   std::vector <TWyklad*> wyklady; // powiazanie
 
};
 
#endif  //_TSTUDENT_H



1



Battle_Hamster

1 / 1 / 1

Регистрация: 27.12.2013

Сообщений: 94

27.05.2014, 00:58

 [ТС]

5

alsav22,
работает! :)
спасибо :)

а можно глупый вопрос?
Программа потом будет правильно находить пути к классам?
И почему такой метод помог, а добавление заголовочных файлов — нет?
Спрашиваю, потому что есть ещё один класс, использующий вектор TStudent, и там при добавлении заголовочного ошибки не было, вот TUczlenia.h:

C++ (Qt)
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
#if !defined(_TUCZELNIA_H)
#define _TUCZELNIA_H
 
#include <iostream>
#include<TStudent.h>
#include<vector>
 
using namespace std;
 
class TUczelnia {
public:
    void dodajStudenta(TStudent *student);
    void usunStudenta();
    void odczytajDaneStudenta(int id);
    void odczytajWszystkichStudentow();
    void dodajWydzial();
    void usunWydzial();
    void odczytajDaneWydzialu();
    void odczytajWszystkieWydzialy();
    TUczelnia(string name, string adres, int telefon);
    void setTelefon(int telefon);
    int getTelefon();
private:
    string name;
    string adres;
    int telefon;
 
  vector <TStudent*> studenci;// proste zagregowanie klasy TStudent z klasą TUczelnia
};
 
#endif  //_TUCZELNIA_H



0



5493 / 4888 / 831

Регистрация: 04.06.2011

Сообщений: 13,587

27.05.2014, 01:04

6

Цитата
Сообщение от Battle_Hamster
Посмотреть сообщение

Программа потом будет правильно находить пути к классам?

Будет.

Цитата
Сообщение от Battle_Hamster
Посмотреть сообщение

И почему такой метод помог, а добавление заголовочных файлов — нет?

У вас, в TStudent.h и в TWyklad.h взаимное включение, из-за этого ошибка. Если в хедере только указатели на класс, то достаточно форвард-объяления класса (без инклуда хедера с классом).

Цитата
Сообщение от Battle_Hamster
Посмотреть сообщение

Спрашиваю, потому что есть ещё один класс, использующий вектор TStudent, и там при добавлении заголовочного ошибки не было,

А тут взаимного включения нет (в TStudent.h нет инклуда TUczlenia.h).



1



Battle_Hamster

1 / 1 / 1

Регистрация: 27.12.2013

Сообщений: 94

27.05.2014, 01:35

 [ТС]

7

alsav22,
ага. спасибо
только я по ходу ещё одну ошибку сделала, можете подсказать что поправить?

в Wyklad.h есть декларация вектора:

C++ (Qt)
1
 std::vector <TStudent*> studenci1;// powiazanie

а в Wyklad.cpp компилятор ругается, что такого вектора не существует:

C++ (Qt)
1
2
3
4
5
void dodajStudenta(TStudent * student)
{
    
    studenci1.push_back(student);
}

ошибка:
D:uniwersityInzeneria Oprogramowaniaproekt_zaliczeniowycppQT_projekt uczelniaTWyklad.cpp:33: ошибка: ‘studenci1’ was not declared in this scope
studenci1.push_back(student);

Добавлено через 1 минуту
весь Wyklad.cpp на всякий:

C++ (Qt)
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
#include "TWyklad.h"
#include"TStudent.h"
TWyklad::TWyklad(string nazwa, int idWykladu) {
    this->nazwa=nazwa;
    this->idWykladu=idWykladu;
    cout<<"Konsruktor klasy TWyklad, utworzono obiekt klasy o nzawie: "<<this->nazwa<<endl;
 
}
 
void TWyklad::setNazwa(string nazwa) {
this->nazwa=nazwa;
 
}
 
string TWyklad::getNazwa() {
    return nazwa;
 
}
 
void TWyklad::setIdWykladu(int idWykladu) {
    this->idWykladu=idWykladu;
 
}
 
int TWyklad::getIdWykladu() {
 
    return idWykladu;
}
 
void dodajStudenta(TStudent * student)
{
 
    studenci1.push_back(student);
}
 
const TStudent* odczytajStudentow();

Добавлено через 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.

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
#include <iostream>
#include <vector>

template <typename type>
void fillvector( std::vector<type>& v );
void displayvector( std::vector<type>& v );

int main()
{
	
	std::vector<int> myvector;
	fillvector( myvector );
	displayvector( myvector );
	
	return 0;
	
}

void fillvector( std::vector<type>& v )
{
	
	int n = 0;
	int i = 1;
	while( n != -1 )
	{

		std::cout << "Enter element number " << i << ": ";
		std::cin >> n;
		v.push_back( n );
		i++;
		
	}
	
	std::cout << "n";
}

void displayvector( std::vector<type>& v)
{
	std::cout << "Vector: ";
	
	for( size_t i = 0; i < v.size(); i++ )
	{
		std::cout << v.at( i ) << " ";
	}
	
	std::cout << "n";
}

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.

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
#include <iostream>
#include <vector>

template <typename T>
void fillvector( std::vector<T>& v ) {
	T n = 0;
	int i = 0;
	while( n != -1 ) {
		std::cout << "Enter element number " << ++i << ": ";
		std::cin >> n;
		if (n != -1)
			v.push_back( n );
	}
	std::cout << "n";
}

template <typename T>
void displayvector( std::vector<T>& v) {
	std::cout << "Vector: ";
	for( size_t i = 0; i < v.size(); i++ )
		std::cout << v.at( i ) << " ";
	std::cout << "n";
}

int main() {
	std::vector<int> myvector;
	fillvector( myvector );
	displayvector( myvector );
	return 0;
}

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

Member Avatar


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

Member Avatar

12 Years Ago

hi ! :)
how can we instanciate the constructor in main() using «new» ?

Member Avatar

12 Years Ago

hi ! :)
in this case ,how can we instanciate the constructor in main() using «new» ?

Member Avatar

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>;

Member Avatar

12 Years Ago

I used this in SystemC implementation :)
it work !! thank you Dazaa :icon_wink:

Member Avatar


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. В интернете я нашел тему, где объясняют, как исправить эту ошибку, но там эта проблема возникала для пользовательского кода и исправлялась просто тем, что убрали один из инклудов, но у меня эта проблема возникла с библиотечным файлом, поэтому я не знаю, что делать. Как вообще могут возникать ошибки в подобных библиотеках?

image

Цитата

Topic starter
Размещено : 30.01.2022 22:07

Родион

Если я правильно понял, то ошибка была в библиотеке. Я скачал более раннюю версию библиотеки QCustomPlot 2.0.0 (2017, а была 2021 года) и выбрал более старую версию компилятора, и у меня все запустилось. 😀 

ОтветитьЦитата

Topic starter
Размещено : 31.01.2022 00:45

Aveal

@rodion-2 отлично! 🙂 

ОтветитьЦитата

Размещено : 31.01.2022 09:38

Понравилась статья? Поделить с друзьями:
  • Error temp too high
  • Error temp lost перевод
  • Error temp lost antminer t17
  • Error telebot break infinity polling
  • Error telebot a request to the telegram api was unsuccessful error code 409