【发布时间】:2014-01-07 09:29:33
【问题描述】:
大家好,新年快乐,
即使在 Visual C++ 的最新版本 Compiler 2013 年 11 月 CTP 中,我在模板中传递“const char”参数时也遇到了一些麻烦!这是在最新的 Visual C++ 编译器中不起作用的简单代码,但可以使用带有选项“std=c++x0”的“g++”,
#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++ 编译器给出该错误,
error C2971: 'A' : template parameter '_parameterChar' : 'a_2' : a local variable cannot be used as a non-type argument
我认为这是对编译器的限制,因为“abcdef”[0],你可以在编译时得到 const char 'a',不是吗?
【问题讨论】:
-
@hetepeperfan:据我所知,它是一个常量表达式,因此可以用作模板参数。你认为究竟是什么使它无法成为一个常量表达式?
-
这段代码使用
g++ (Ubuntu/Linaro 4.8.1-10ubuntu9) 4.8.1编译得很好。问题可能是您使用的编译器在编译时没有推断出"abcdef"[0]的值? -
对于它的价值,Clang 也拒绝了这一点。但我很难看出是什么使
"abcdef"[0]无法成为常量表达式,所以我不能说哪个编译器是正确的。 -
@MikeSeymour 我认为它在 C++11 中可能是合法的,但在 C++11 之前的版本中肯定不是。 (如果 g++ 支持它作为扩展,我也不会感到惊讶,即使在 C++11 之前也是如此。)
-
奇怪的是
const char a_2 = "abcde"[0];是合法的,但是在模板参数中被拒绝了。
标签: c++ templates parameter-passing