Home >Backend Development >C++ >How to solve C++ compilation error: 'invalid use of template-name without an argument list'?
Solution to C compilation error: 'invalid use of template-name without an argument list', how to solve it?
In C programming, we often encounter various compilation errors. One of the common errors is "invalid use of template-name without an argument list". This error is usually caused by incorrect usage of the template name. This article will explain the causes of this error and provide some solutions.
First, let us look at a code example to simulate this error:
template <typename T> class MyClass { public: void print(T value) { cout << value << endl; } }; int main() { MyClass myObject; myObject.print(10); return 0; }
In the above code, we define a template class MyClass, which has a member function print() Used to print the passed in value. In the main() function, we create a MyClass object myObject and try to call its print() function to print the integer 10.
However, when we try to compile this code, we encounter the following error message:
error: invalid use of template-name 'MyClass' without an argument list
The reason for this error is that we are missing a template parameter when creating the myObject object. In C, template parameters must be provided when a template class is instantiated. In this case, we should tell the compiler that we want to instantiate a MyClass object that accepts an integer type.
To resolve this error, we need to provide the correct template parameters. Modify the above code as follows:
int main() { MyClass<int> myObject; myObject.print(10); return 0; }
By using bd43222e33876353aff11e13a7dc75f6 after MyClass, we tell the compiler that we want to instantiate a MyClass object that accepts an integer type. Now we compile the code again and no longer encounter the previous error.
In addition, if we want to create a MyClass object that accepts other types, we can use template parameters like the following:
int main() { MyClass<double> myObject; myObject.print(3.14); return 0; }
In this code, we create a MyClass object that accepts a double precision float A MyClass object of point type and calls its print() function to print 3.14.
To summarize, the 'invalid use of template-name without an argument list' error is caused by not providing the correct template parameters when using the template class. The solution to this error is to provide the correct template parameters to the template class.
Hopefully through the above explanation and sample code, you can better understand and solve this common compilation error. When writing C code, don't panic when you encounter this error, carefully check the relevant template usage and make sure to provide the correct template parameters.
The above is the detailed content of How to solve C++ compilation error: 'invalid use of template-name without an argument list'?. For more information, please follow other related articles on the PHP Chinese website!