curious student
curious student

Reputation: 332

C++: Passing arguments through templates Vs through function parameters

Is there any purpose for sending parameters through templates? If so, how does this differ from sending parameters through the internal stack? Example:

void myMethod(int argument){//Do something with *argument* };

vs

template<int argument>
void myMethod(){//Do something with *argument* };

In the book Thinking in C++, volume 1, 2nd edition, under the chapter Templates in depth , there are only a few words about non-type template arguments, and I feel I didn't quite fully understand their purpose.

EDIT: Thanks for the explanations. If I could, I'd mark both answers as they both complemented each other.

Upvotes: 4

Views: 112

Answers (2)

The Quantum Physicist
The Quantum Physicist

Reputation: 26266

The difference is that with templates, the values are decided and fixed at compile-time; i.e., when you compile your program. You can't, ever, change them after the compilation is done, and they're considered constants forever.

So, with:

template<int argument>
void myMethod(){//Do something with *argument* };

If you call myMethod<5>(), then the value of argument is always 5, and the function practically doesn't have any arguments at run-time. Now if you call myMethod<6>(), the compiler will recreate the same function but with another constant value. So you'll have 2 functions at run-time.

On the other hand, with normal methods, you can change them at run-time, i.e., while the program is running. Calling the function again will just execute the same code with different argument values.

Example:

template <int L>
void DoSomething()
{
    int a[L];  //this works fine here! Becasue L is just a constant that is resolved at compile-time
    for(int i = 0; i < L; i++)
    {
        //do stuff
    }
}


void DoSomething(int L)
{
    int a[L];  //this won't work, because L is a variable that can be set while the program is running
    for(int i = 0; i < L; i++)
    {
        //do stuff
    }
}

Upvotes: 1

marcinj
marcinj

Reputation: 49986

Here:

void myMethod(int argument){//Do something with *argument* };

argument is passed to myMethod during runTime, so different values can be passed.

Here:

template<int argument>
void myMethod(){//Do something with *argument* };

argument template parameter is passed at compile time.

Non type template parameters have greater implications when used with classes, ie.:

template<int N>
class Test{};

typedef Test<1> test1_type;
typedef Test<2> test2_type;

static_assert(std::is_same<test1_type, test2_type>::value == false, "");

test1_type and test2_type are different types

Upvotes: 1

Related Questions