简体   繁体   English

c ++模板参数中的常量表达式

[英]constant expression in c++ template argument

I have a template, that takes a char argument like: 我有一个模板,需要一个char参数,例如:

A<'T'>

I am storing my T in a variable like: 我将我的T存储在像这样的变量中:

const char ch = str[0]; //str is a string from my program // str是我程序中的字符串

constexpr char ch = str[0]; // this doesnt work either for me //这对我都不起作用

I am trying to achieve this: 我正在努力实现这一目标:

A<ch>();

I am using gcc 4.7 and have dabbled with constexpr but I havent been able to get that work 我正在使用gcc 4.7并接触过constexpr,但是我还无法完成这项工作

Any idea of a way to get this to work? 有办法使它起作用吗? Any help is appreciated 任何帮助表示赞赏

This can only work if everything is a constant expression: 仅当所有内容均为常量表达式时,此方法才有效:

constexpr char str[] = "Hello World";
constexpr char ch = str[0];
A<ch> x;

If the contents of str are defined at runtime, then there is no way to achieve that. 如果str的内容是在运行时定义的,则没有办法实现。 The compiler requires your template value to be set during compilation. 编译器要求您在编译期间设置模板值。

That is why this is valid: 这就是为什么这是有效的:

A<'a'>();

Since 'a' is a constant value, known during compilation. 由于'a'是一个恒定值,在编译期间会知道。 But this: 但是这个:

void foo(const std::string &value) {
    A<value[0]> t;
}

Is not, since value[0] , despite being a constant value, is not known during compilation. 不会,因为value[0]尽管是常数,但在编译过程中未知。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM