据我所知,如果静态const成员是整数类型,则只能在它们的声明的同一行初始化.但是,我仍然能够初始化并使用一些静态const双精度:
// compiles and works, values are indeed doubles
struct Foo1{
static const double A=2.5;
static const double B=3.2;
static const double C=1.7;
};
// compiles, but values are cast to int
struct Foo2{
static const int A=2;
static const int B=3;
static const double C=B/A; //becomes 1
};
// does not compile, Foo3::B cannot appear in a constant-expression
struct Foo3{
static const int A=2;
static const double B=3;
static const double C=A/B;
};
// does not compile, …Run Code Online (Sandbox Code Playgroud) 我正在阅读关于const_cast的内容,它看起来不安全,而且不是很有帮助.在SO中关于它的最佳答案表明它在这样的场景中会有用:
void func(const char* param, bool modify){
if(modify)
//const_cast and change param
// stuff that do not change param
}
Run Code Online (Sandbox Code Playgroud)
虽然这是一种可能的用法,但它有风险,因为你必须正确地提供"修改"的值,否则你会得到一个未定义的行为,因为你正在改变应该是常量的东西.我想知道你是否可以实现相同的功能,而不必提供额外的参数,为此你很可能需要检查const限定符的存在.
我发现关闭的东西是std函数is_const,但它似乎仅限于一种不同的用法:
is_const<const int>::value //returns true
is_const<int>::value // returns false
const int myVar=1;
is_const<myVar>::value // what it would look like ( does not compile)
Run Code Online (Sandbox Code Playgroud)
我也尝试过使用类似的功能签名,只有"const"限定符不同,但这被认为是重新定义.所以可以做到这一点吗?如果是这样,怎么办呢?
为了方便命名,我在代码中写了这些看似无害的行:
struct Foo{
double vec[2];
double& a=vec[0],b=vec[1];
};
Run Code Online (Sandbox Code Playgroud)
但由于某种原因,变量"a"工作正常而"b"没有(它返回垃圾).这很奇怪,因为它似乎是一种有效的方式来声明它们.然后我测试了一些替代方法:
#include <iostream>
using namespace std;
struct Foo{
double vec[2];
double& a=vec[0],b=vec[1]; //does not work
double& c=vec[0];
double& d=vec[1]; //works
double ev,fv;
double& e=ev,f=fv; // does not work
double& g,h; // does not work
Foo() : g(vec[0]) ,h(vec[1]){};
void bar(){
vec[0]=1;
vec[1]=2;
ev=1;
fv=2;
cout<<"a: "<<a<<endl;
cout<<"b: "<<b<<endl;
cout<<"\nc: "<<c<<endl;
cout<<"d: "<<d<<endl;
cout<<"\ne: "<<e<<endl;
cout<<"f: "<<f<<endl;
cout<<"\ng: "<<g<<endl;
cout<<"h: "<<h<<endl;
double& i=vec[0], j=vec[1]; //works
cout<<"\ni: "<<i<<endl;
cout<<"j: "<<j<<endl;
}
}; …Run Code Online (Sandbox Code Playgroud)