预处理程序命令中的sizeof不会编译,错误为C1017 [英] sizeof in preprocessor command doesn't compile with error C1017

查看:42
本文介绍了预处理程序命令中的sizeof不会编译,错误为C1017的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用预处理程序命令来控制代码执行路径.因为这样可以节省运行时间.

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

#if(sizeof(T)== 1 未能正确执行错误:C1017

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

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

    inline void test()
    {
        String<char>::showSize();
        String<wchar_t>::showSize();
    }

推荐答案

预处理器在C ++编译器之前运行.它对C ++类型一无所知.仅预处理器令牌.

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

虽然我希望任何像样的编译器都能优化 if(sizeof(T)== 1),但是在C ++ 17中,您可以使用新的 if对其进行明确说明constexpr :

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<typename T>
class String
{
public:
    static void showSize()
    {
        if constexpr (sizeof(T) == 1) {
            std::cout << "char\n";
        } else {
            std::cout << "wchar_t\n";
        }
    }
};

实时演示

在C ++ 17之前的版本中,它不那么简单.您可以使用一些部分专业化的恶作剧.它不是特别漂亮,我认为这种情况下它甚至不会更加高效,但是在其他情况下也可以使用相同的模式:

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 <typename T, size_t = sizeof(T)>
struct size_shower
{
    static void showSize()
    {
        std::cout << "wchar_t\n";
    }
};

template <typename T>
struct size_shower<T, 1>
{
    static void showSize()
    {
        std::cout << "char\n";
    }
};

template<typename T>
class String
{
public:
    static void showSize()
    {
        size_shower<T>::showSize();
    }
};

实时演示

在这种情况下,您可以直接专门化 String ,但是我假设在您的实际情况下,它有其他成员您不想重复.

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.

这篇关于预处理程序命令中的sizeof不会编译,错误为C1017的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆