May 072013

What will be the output of the below C++ program:

// Template Function - Not taking class
template <class T, int i> int myFun(){
    T x = 10;
    i = 20; 

int main(){
   fun<int, 4>();
   return 0;


The below program will result in compile time error.

The template function uses two template arguments. First is of type class (or typename and second is a non-type.

In class type argument we have to pass a typename (like char, int, float etc.) or class name (user defined class).

In non-type argument we have to pass a constant value (derivable at compile time). this value can be used to specify the size of array (because it is constant).

template <int i> int myFun(){
    int arr[i]; //OK because i is compile time constant

Because the non-type is compile time constant, hence it cannot be changed. We are trying to change i in original program

    i = 20;

Hence, an error.

  2 Responses to “Find the output of C++ Program”

Comments (2)
  1. great good work.. useful…

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>