Error "cannot convert template argument" for pointer parameters even when using

Let's say that I have a template class declared as follows:

template< int *x > struct y { int *b; y() { b = x; }} 

I need a template parameter as a constant memory address - this is inline code. If I try to create it this way: (gcc 4.8.1 compiler with -std = gnu ++ 11)

 y< 1 > c; 

I will get the error "could not convert the template argument '1' to 'int *'" and it is fine and in accordance with the standard. I understand.

My problem is that casting to pointers doesn't work either:

 y< (int *)1 > d; y< reinterpret_cast<int *>(1) > e; 

error: cannot convert template argument '1u' to 'int *'

in both cases. Why is this? The template argument has already been converted, right?

+6
source share
2 answers

This is prohibited by the C ++ standard, section ยง14.3.2

The template argument for a non-piggy template without a template must be one of the following:

  • integral constant expression of an integral or enumerated type; or
  • asymmetric pattern name; or
  • the address of an object or function with external communication , including function templates and function templates, but excluding non-static members of the class, expressed as id-expression, where a is optional if the name refers to a function or array, or if the corresponding parameter template is a link; or
  • pointer to an element expressed as described in 5.3.1

Solution :

Use a variable with external binding as a template parameter:

 template< int *x > struct y { int *b; y() { b = x; } }; extern int i; // Extern static int j = 1; // Static int z = 1; // Global int main() { y< &i > c1; y< &j > c2; y< &z > c3; return 0; } 

Real-time example here .

+2
source

I donโ€™t know exactly what you have, but I assume that you are trying to simulate certain hardware registers. Will it satisfy your needs?

 #include <cstdint> template< uintptr_t x > struct y { int *const b; y() : b(reinterpret_cast<int*>(x)) {} }; int main() { y< 42 > c; return *cb; } 
0
source

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


All Articles