Three Questions

1. Can I get the size of an array using sizeof() ?
2. Can a class template have a member function that it a template itself, like this:

1
2
3
4
5
6
template<class T>
class A
{
    T member[4];
    template <class U> void func(U* ptr);
}


3. What do these keywords do: explicit , mutable , volatile
Last edited on
1. Only for a fixed length array whose size can be known by the compiler at the point of the sizeof,
and even then sizeof returns the size in bytes, which may not be the same as the number of elements.

2. Yes. However, constructors, which are not "member functions" according to the standard, may
not be templated if the class is itself a template.

3a. Example.
1
2
3
4
5
6
7
8
9
10
11
12
class string {
  public:
      string( const char* s );
};

void frobnicate( string s ) {
  // .. do stuff
}

int main() {
    frobnicate( "hello world" );
}


The function call in main compiles and works because the compiler implicitly calls
string::string( const char* ) to turn the "hello world" text into a string object by
constructing a temporary.

You can turn off this implicit construction by declaring string's constructor explicit:

1
2
3
4
class string {
  public:
     explicit string( const char* s );
};


And now the call to frobnicate in main will generate a compile error.

Explicit is only used for constructors that can be called with exactly one parameter,
and should never be used for copy constructors.

3b. By definition, a const member function cannot modify any of the data members of
the object. You can turn this off as well by declaring a data member to be mutable.
This means that the data member may be changed by const member functions.

3c. By definition in the standard, volatile tells the compiler not to reorder
things (during optimization) around assignments to the variable declared volatile.

[EDIT: Only 90% sure about 3c, but 100% sure about the rest.]
Last edited on
You are correct about 3c.

The volatile keyword tells the compiler that the object in question may be modified by methods not visible to the compiler. This is useful when dealing with hardware directly.
To get the number of elements,divide it by the int size.

1
2
3
4
5
6
#include<iostream>
int main()
{
int a[10];
std::cout<<sizeof(a)/sizeof(int);
}
Last edited on
For one-dimensional arrays of a general type, divide size of whole array by the size of element 0:

1
2
3
4
5
int main( )
{
   double ar[10] ;
   size_t n = sizeof ar / sizeof ar[0] ; // n elements
}
1
2
3
template< typename T, size_t N >
size_t array_size( T (&)[ N ] )
{ return N; }


is the best C++ solution.

(Note: parameter may need to be a const reference to an array. I'm used to GCC 3.3 which is broken and
will not allow the more correct const reference to an array.)

Topic archived. No new replies allowed.