在预处理器指令中使用模板参数? [英] Use a template parameter in a preprocessor directive?

查看:128
本文介绍了在预处理器指令中使用模板参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在预处理器指令中使用非类型常量模板参数?这里是我想到的:

Is it possible to use a non-type constant template parameter in a preprocessor directive? Here's what I have in mind:

template <int DING>
struct Foo
{
    enum { DOO = DING };
};

template <typename T>
struct Blah
{
    void DoIt()
    {
        #if (T::DOO & 0x010)

        // some code here

        #endif
    }
};



当我尝试使用 Blah< Foo< 0xFFFF> ,VC ++ 2010抱怨一些关于不匹配的括号的行,我们试图使用 #if 。我猜测预处理器真的不知道任何关于模板和这种事情只是不在其域中。说啥?

When I try this with something like Blah<Foo<0xFFFF>>, VC++ 2010 complains something about unmatched parentheses in the line where we are trying to use #if. I am guessing the preprocessor doesn't really know anything about templates and this sort of thing just isn't in its domain. What say?

推荐答案

不,这是不可能的。预处理器是非常愚蠢的,它不知道你的程序的结构。如果 T :: Doo 没有在预处理器中定义(并且不能是,因为 :: ),它不能评估那个表达式并且会失败。

No, this is not possible. The preprocessor is pretty dumb, and it has no knowledge of the structure of your program. If T::Doo is not defined in the preprocessor (and it can't be, because of the ::), it cannot evaluate that expression and will fail.

但是,你可以依靠编译器为你做聪明的事情:

However, you can rely on the compiler to do the smart thing for you:

        if (T::Doo & 0x010) {
            // some code here
        }

即使在较低的优化设置下,常量表达式和死分支也会优化,因此您可以安全地执行此操作而不会产生任何运行时开销。

Constant expressions and dead branches are optimized away even at the lower optimization settings, so you can safely do this without any runtime overhead.

这篇关于在预处理器指令中使用模板参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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