问题
Hi and happy new year to everyone,
I have some troubles passing passing a "const char" parameter in templates even in the last versión Compiler Nov 2013 CTP of Visual C++! This is the simple code that doesn't work in the latest Visual C++ compiler but yes with "g++" with the option "std=c++x0",
#include <stdlib.h>
template<char _parameterChar>
class A
{
char varChar;
public:
A(){ varChar = _parameterChar; }
~A(){}
};
int main(int argc, char* argv[])
{
const char a_1 = 'a';
const char a_2 = "abcdef"[0]; // This instruction gets a constant 'a'.
A<'a'> first_A; // compile ok!
A<a_1> second_A; // compile ok!
A<a_2> third_A; // ---> This not compiles!! Why not ?!?!?!
return 0;
}
Visual C++ compiler gives that error,
error C2971: 'A' : template parameter '_parameterChar' : 'a_2' : a local variable cannot be used as a non-type argument
I think that is a restricción of compiler, because "abcdef"[0], you could get the const char 'a' at compile time, isn't it ?
回答1:
The simple answer is that the standard says that "abcdef"[0]
is not a constant expression. Logically, the compiler could probably work it out, but the standard doesn't list it in the allowed operations. Evaluation of the expression involves an lvalue to rvalue conversion, and only a very limited number of lvalue to rvalue conversions are allowed. (Actually, it may be legal in C++11. But if this is the case, it would be a new feature, and possibly not implemented by your compiler.)
回答2:
James Kanze says the "abcdef"[0] is not a constant expression, but I think it is from standard.
standard 5.19.3
An integral constant expression is an expression of integral or unscoped enumeration type, implicitly converted to a prvalue, where the converted expression is a core constant expression.
standard 5.19.2
an lvalue-to-rvalue conversion (is not a core constant expression) unless it is applied to:
a non-volatile glvalue of integral or enumeration type that refers to a non-volatile const object with a preceding initialization, initialized with a constant expression [ Note: a string literal (2.14.5) corresponds to an array of such objects. —end note ],
回答3:
Currently this code compiles and works as expected on Visual Studio 2017 (Windows). No need to do a specific configuration settings, just enough default console application. Unfortunately I haven't ability to check it on previous versions of VS.
来源:https://stackoverflow.com/questions/20968026/some-trouble-passing-a-const-char-parameter-in-templates-even-in-visual-c-co