what's the purpose of typename assignment inside templates

前端 未结 6 896
后悔当初
后悔当初 2021-01-02 08:07

I have come across this piece of code (I\'m trying to include all details in case I\'m missing something):

template< typename TYPE = TYPE_with_an_arbitrar         


        
6条回答
  •  醉梦人生
    2021-01-02 08:45

    This is called 'default template argument' and specifies which type is used, when none is specified - alike default function parameters. This technique is widely used for classes - look at definition of std::vector or std::string, and you will see they have multiple default type parameters.

    Best use for default type parameters for function templates is when type argument cannot be easily deduced from actual arguments, and it is not specified explicitly - then compiler will use default one. In your example there is no need for default types, because it can be easily deduced from actual call parameters.

    Until C++0x default type parameters were allowed only for class templates - they were not possible to use with function templates. With C++0x it changed, but some older compilers (for example Visual C++ 2008) would not let you to use them.

提交回复
热议问题