C ++ Constant Preprocessor Macros and Templates

Let's say I have the following very simple macro, as well as some code to output it:

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

This produces 309, and if you look at the assembly, you will see:

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 135hperfectly translates to 309 decimal places. Everything has been compiled to constant.


Now let's say that you have a template class as such:

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

Then the following beautifully prints number 32:

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

Both of these things work individually, the problem arises when you try to combine them:

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

In a visual studio, this gives:

1>. \ ShiftCompare.cpp (187): error C2975: "X": invalid template argument for "Printer", expected constant expression of compilation time
    1>. \ ShiftCompare.cpp (127): see 'X' declaration

, SIMPLEHASH("Blah") , .

, , " "? , , "" ?

- , ?

+3
1

, , .

, , Printer, , .

+5

Source: https://habr.com/ru/post/1769823/


All Articles