简体   繁体   English

C ++常量预处理器宏和模板

[英]C++ Constant preprocessor macros and templates

So say I have the following very simple macro, along with a bit of code to output it: 所以说我有以下非常简单的宏,以及一些输出它的代码:

#define SIMPLEHASH(STRING) STRING[1] + STRING[2] + STRING[3]
std::cout <<  SIMPLEHASH("Blah");

This outputs 309, and if you view the assembly you can see: 这输出309,如果您查看程序集,您可以看到:

00131094  mov         ecx,dword ptr [__imp_std::cout (132050h)] 
0013109A  push        135h 
0013109F  call        dword ptr [__imp_std::basic_ostream<char,std::char_traits<char> >::operator<< (13203Ch)] 

Where 135h translates nicely into 309 decimal. 其中135h很好地转换成309小数。 Everything was compiled away to a constant. 一切都被编译成一个常数。


Now, say you have a template class as such: 现在,假设你有一个模板类:

template<int X> class Printer{
public:
 void Print(){
  std::cout << X;
 }
};

Then the following will nicely print the number 32: 然后以下将很好地打印数字32:

Printer<32> p;
p.Print();

Both these things work individually, the problem comes when you try to combine them: 这两件事都是单独的,当你试图将它们组合起来时就会出现问题:

#define SIMPLEHASH(STRING) STRING[1] + STRING[2] + STRING[3]
 Printer<SIMPLEHASH("Blah")> p;
 p.Print();

In visual studio this gives: 在visual studio中,这给出了:

1>.\\ShiftCompare.cpp(187) : error C2975: 'X' : invalid template argument for 'Printer', expected compile-time constant expression 1>。\\ ShiftCompare.cpp(187):错误C2975:'X':'Printer'的模板参数无效,预期的编译时常量表达式
1> .\\ShiftCompare.cpp(127) : see declaration of 'X' 1>。\\ ShiftCompare.cpp(127):看'X'的声明

Despite the fact that SIMPLEHASH("Blah") can be reduced to a constant at compile time, as seen in the first example. 尽管SIMPLEHASH("Blah")可以在编译时减少到常量,如第一个例子中所示。

So, what gives, is there a way to tell the compiler "evaluate this first"? 那么,有什么方法可以告诉编译器“先评估一下”? are templates naturally "before" macros in preprocessor evaluation? 在预处理器评估中自然是“之前”的模板?

Does anyone see any way I can get these two to work together? 有谁看到我可以让这两个人一起工作?

Macros are evaluated before the source is fully parsed and preprocessing has nothing at all to do with templates. 在完全解析源之前评估宏,并且预处理与模板没有任何关系。

The problem is that the template argument with which you instantiate Printer must be a constant expression and you cannot use a string literal in a constant expression. 问题是您实例化Printer的模板参数必须是常量表达式,并且不能在常量表达式中使用字符串文字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM