String literals not allowed as non type template parameters

前端 未结 5 1707
小鲜肉
小鲜肉 2020-11-30 02:11

The following quote is from C++ Templates by Addison Wesley. Could someone please help me understand in plain English/layman\'s terms its gist?

5条回答
  •  时光说笑
    2020-11-30 02:51

    As mentioned in other answers, a string literal cannot be used as a template argument. There is, however, a workaround which has a similar effect, but the "string" is limited to four characters. This is due to multi-character constants which, as discussed in the link, are probably rather unportable, but worked for my debug purposes.

    template
    class NamedClass
    {
        std::string GetName(void) const
        {
            // Evil code to extract the four-character name:
            const char cNamePart1 = static_cast(static_cast(nFourCharName >> 8*3) & 0xFF);
            const char cNamePart2 = static_cast(static_cast(nFourCharName >> 8*2) & 0xFF);
            const char cNamePart3 = static_cast(static_cast(nFourCharName >> 8*1) & 0xFF);
            const char cNamePart4 = static_cast(static_cast(nFourCharName       ) & 0xFF);
    
            std::ostringstream ossName;
            ossName << cNamePart1 << cNamePart2 << cNamePart3 << cNamePart4;
            return ossName.str();
        }
    };
    

    Can be used with:

    NamedClass<'Greg'> greg;
    NamedClass<'Fred'> fred;
    std::cout << greg.GetName() << std::endl;  // "Greg"
    std::cout << fred.GetName() << std::endl;  // "Fred"
    

    As I said, this is a workaround. I don't pretend this is good, clean, portable code, but others may find it useful. Another workaround could involve multiple char template arguments, as in this answer.

提交回复
热议问题