C ++: passing arguments through Vs templates via function parameters

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

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

against

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

In the book Thinking in C ++ , volume 1, 2nd edition, in the section "Templates in depth", there are only a few words about the template arguments that are different from the type, and I feel that I did not fully understand their purpose.

EDIT: Thanks for the explanation. If I could, I would mark both answers as they both complemented each other.

+4
source share
2 answers

, ; .. . , .

, :

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

myMethod<5>(), argument 5, . , myMethod<6>(), , . , 2 .

, , . .

:

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
    }
}
+1

:

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

myMethod runTime, .

:

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

argument .

, ..:

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 test2_type

+1

Source: https://habr.com/ru/post/1671353/


All Articles