Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this code legal in C++

I just found that when it comes to templates this code compiles in g++ 3.4.2 and works unless m() is not called:

template <typename T>
class C
{
     T e;

     public:
        C(): e(0) {};

    void m()
    {
        e = 0;
    };
 };

Now one may create and use instance

C<const int> c;

Until c.m() is not called there are no compile errors but is this legal?

like image 823
mip Avatar asked Nov 26 '09 22:11

mip


People also ask

Can you use this in C code?

It is not a reserved identifier, so you are free to use it.

Why #is used in C?

In C/C++, the # sign marks preprocessor directives. If you're not familiar with the preprocessor, it works as part of the compilation process, handling includes, macros, and more. It actually adds code to the source file before the final compilation.

Which is a illegal declaration?

1. Which of the following declaration is illegal? Explanation: char[] str is a declaration in Java, but not in C. 2.

Can I code C in Mobile?

Android is based on Linux Kernel so it's definitely possible to compile & run C/C++ programs on Android. C is quite cross-platform , so a C Program written in Windows can Run on Linux ( and android ) and vice versa.


1 Answers

Yes, this is legal. The template specification is that until a method is instantiated, it doesn't exist and therefor is not checked by the compiler. Here's the relevant bit from the spec:

14.7.1 - Implicit instantiation

-9- An implementation shall not implicitly instantiate a function template, a member template, a non-virtual member function, a member class or a static data member of a class template that does not require instantiation.

like image 81
Don Neufeld Avatar answered Oct 23 '22 11:10

Don Neufeld