Wednesday, 14 November 2018

Void pointer as template argument in C++

The following does not compile:




template
class X {
// ...
};

int r;

int main()
{
X<&r> x;


return 0;
}


The error message is




x.cc:10:6: error: could not convert template argument ‘& r’ to ‘void*’





Explicitly casting &r to (void *) doesn't help either. The error message becomes:




x.cc:10:14: error: could not convert template argument ‘(void*)(& r)’ to ‘void*’




Which part of the standard specifies that behaviour?
The GCC version is gcc version 5.2.1 20151003 (Ubuntu 5.2.1-21ubuntu2)




Edit:



Please note that using e.g. int * instead of void * works as expected.



Edit: (answering myself)



It does not work with gcc HEAD 6.0.0 20151016 (experimental) when specifying -std=c++1z, neither with implicit nor with explicit casting to "void *".



It does work with clang HEAD 3.8.0 (trunk 250513) and has been since (at least) clang 3.6.0 (tags/RELEASE_360/final) when specifying --std=c++1z and explicitly casting to *void *".
Without the explicit cast, clang complains as follows:





x.cc:10:7: error: conversion from 'int *' to 'void *' is not allowed in a converted constant expression




Responsible for fixing this bug in the c++ language specification is N4268 which clang already implements.

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...