Print characters coming in one of the 2 strings (and not in both)
April 24, 2013
Function to swap strings in C
May 19, 2013

Find the output of C++ Program

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

Solution:

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 Comments

  1. kishu says:

    great good work.. useful…

Leave a Reply

Your email address will not be published. Required fields are marked *