模板函数参数的默认值

Default value for template function argument

本文关键字:默认值 参数 函数      更新时间:2023-10-16

注意:我没有C++11

我需要模板函数参数的默认值,但似乎 c++将跳过默认参数的扣除...

struct mode1 {};
struct mode2 {};
template <typename T>
void myFunc(int value, T mode = mode1())
{
    if(std::is_same<T, mode1>::value)
    {
        std::cout << "foo";
    }
    else if(std::is_same<T, mode2>::value)
    {
        std::cout << "bar";
    }
}

但是我怎样才能实现,这个电话将起作用:

myFunc(20); /* Defaults to mode1 */

为什么我会使用它?因为优化...在我的现实生活中,我会在这段代码中使用它:

template <typename TokenType>
        HGStringBasic Tokenize(const _ElemT* tokens, size_type uTokenIndex, size_type uIndex = 0, size_type uEndIndex = npos, TokenType tokenType = tokenTypeChar()) const
        {           
            size_type uPosInStr;
            size_type uCurrToken;
            if(uEndIndex == npos)
            {
                uEndIndex = this->Length();
            }
            for( uCurrToken = 0 ; uIndex < uEndIndex ; (uIndex = uPosInStr+1), (++uCurrToken) )
            {
                if(std::is_same<TokenType, tokenTypeChar>::value)
                    uPosInStr = this->PosBrk(tokens, uIndex);
                else if(std::is_same<TokenType, tokenTypeString>::value)
                    uPosInStr = this->Pos(tokens, uIndex);
                if(uCurrToken == uTokenIndex) 
                {                       
                    if(uPosInStr == npos)
                        return this_type(&m_data[uIndex], uEndIndex - uIndex);
                    return this_type(&m_data[uIndex], (uPosInStr < uEndIndex ? uPosInStr : uEndIndex) - uIndex);
                }
                if(uPosInStr == npos)
                    break;
            }
            return this_type();
        }

是的,模板节选扣除中不考虑默认值。

无法从函数默认参数的类型推导出类型模板参数

您可以添加重载,例如

template <typename T>
void myFunc(int value, T mode)
{
    ...
}
void myFunc(int value) {
    myFunc(value, mode1());
}