sizeof in preprocessor command doesn't compile with error C1017

后端 未结 4 642
迷失自我
迷失自我 2021-01-29 16:46

I want to use preprocessor command to control code executive path. Because in this way can save runtime time.

#if (sizeof(T)==1 doesn\'t comple with error:

4条回答
  •  终归单人心
    2021-01-29 17:08

    The preprocessor runs before the C++ compiler. It knows nothing of C++ types; only preprocessor tokens.

    While I would expect any decent compiler to optimize away an if (sizeof(T) == 1), you can be explicit about it in C++17 with the new if constexpr:

    template
    class String
    {
    public:
        static void showSize()
        {
            if constexpr (sizeof(T) == 1) {
                std::cout << "char\n";
            } else {
                std::cout << "wchar_t\n";
            }
        }
    };
    

    Live Demo

    Pre C++17 it's a bit less straightforward. You could use some partial-specialization shenanigans. It's not particularly pretty, and I don't think it will even be more efficient in this case, but the same pattern could be applied in other situations:

    template 
    struct size_shower
    {
        static void showSize()
        {
            std::cout << "wchar_t\n";
        }
    };
    
    template 
    struct size_shower
    {
        static void showSize()
        {
            std::cout << "char\n";
        }
    };
    
    template
    class String
    {
    public:
        static void showSize()
        {
            size_shower::showSize();
        }
    };
    

    Live Demo

    In this case you could directly specialize String, but I'm assuming in your real situation it has other members that you don't want to have to repeat.

提交回复
热议问题