Reason for using non-type template parameter instead of regular parameter?

前端 未结 6 898
刺人心
刺人心 2020-12-03 00:54

In C++ you can create templates using a non-type template parameter like this:

template< int I >
void add( int& value )
{
  value += I;
}

int main         


        
6条回答
  •  生来不讨喜
    2020-12-03 01:55

    In that particular instance, there's not really any advantage. But using template parameters like that, you can do a lot of things you couldn't do otherwise, like effectively bind variables to functions (like boost::bind), specify the size of a compile-time array in a function or class (std::array being a ready example of that), etc.

    For instance, with that function, you write a function like

    template
    void apply(T f) {
        f(somenum);
    }
    

    Then you can pass apply a function:

    apply(&add<23>);
    

    That's an extremely simple example, but it demonstrates the principle. More advanced applications include applying functions to every value in a collection, calculating things like the factorial of a function at compile time, and more.

    You couldn't do any of that any other way.

提交回复
热议问题