C++ 如果我的类是一个文本类,那么将我的类的对象声明为constexpr是多余的吗?
我有一个constexpr类调试:C++ 如果我的类是一个文本类,那么将我的类的对象声明为constexpr是多余的吗?,c++,oop,constexpr,C++,Oop,Constexpr,我有一个constexpr类调试: struct Debug { constexpr Debug(bool a, bool b, bool c) : a(a), b(b), c(c) {} bool a, b, c; constexpr bool get() const { return a; } }; int main() { Debug dbg(true, false, false); // is dbg constexpr object? constexpr Debu
struct Debug {
constexpr Debug(bool a, bool b, bool c) : a(a), b(b), c(c) {}
bool a, b, c;
constexpr bool get() const { return a; }
};
int main() {
Debug dbg(true, false, false); // is dbg constexpr object?
constexpr Debug dbg2(0, 0, 0); // is constexpr redundant here?
}
正如您所看到的,dbg
是一个constexpr对象,因为它是用constexpr构造函数初始化的,所以如果我用constexpr对它进行限定,这有什么意义
- 我不知道
和dbg
之间的区别。多谢各位dbg2
dbg2
。作为一个例子,考虑即将出现的允许任意非类型模板参数的C++ 20特性:
template <Debug> void f() { }
template void f(){}
根据上述定义,f()
将编译,而f()
将不编译
f<dgb>();
f();
:7:29:注意:模板参数推断/替换失败:
:13:12:错误:“dbg”的值在常量表达式中不可用
13 | foo();//错误
| ^
:10:9:注意:“dbg”未声明为“constexpr”
10 |调试dbg(真、假、假);//dbg constexpr是对象吗?
这在C++11中也很重要。你可以说:
template <bool> void g() { }
g<dgb2.a>();
template void g(){}
g();
但不是:
g<dgb.a>();
g();
简单演示两个变量的不同之处:
struct Debug {
constexpr Debug(bool a, bool b, bool c) : a(a), b(b), c(c) {}
bool a, b, c;
constexpr bool get() const { return a; }
};
int main() {
Debug dbg(true, false, false); // dbg is not a constant
constexpr Debug dbg2(0, 0, 0); // constexpr makes this a constant expression
// *** Begin demo ***
dbg.a = false;
//dbg2.a = false; //< error: assignment of member 'Debug::a' in read-only object
// *** End demo ***
}
struct调试{
constexpr调试(bool a,bool b,bool c):a(a),b(b),c(c){
布尔a,b,c;
constexpr bool get()const{return a;}
};
int main(){
Debug dbg(true,false,false);//dbg不是常量
constexpr调试dbg2(0,0,0);//constexpr使其成为常量表达式
//***开始演示***
dbg.a=假;
//dbg2.a=false;//<错误:在只读对象中分配成员'Debug::a'
//***结束演示***
}
dbg
的值可以更改,而dbg2
的值不能更改
若要获取作为常量表达式的
Debug
对象,您需要构造函数中的constexpr
限定符(允许将Debug
对象标记为常量表达式)和变量声明中的constexpr
限定符(将该对象标记为常量表达式).我认为这没有什么区别。如果Debug
有一些字段,这可能会有所不同。@HolyBlackCatDebug
有三个bool
成员。我会把它加回去。@HolyBlackCat:dbg
可以调用非consexpr成员函数,而dbg2
只能调用constexpr
方法。@Maestro我想这不是关于方法是constexpr
,而是const
限定的,constexpr
函数可以在编译时和运行时调用,而constexpr
对象保证在编译时存在(作为常量)。OK。谢谢明白了。最后一个问题:这是否意味着我不能声明非文本类的constexpr
对象?
struct Debug {
constexpr Debug(bool a, bool b, bool c) : a(a), b(b), c(c) {}
bool a, b, c;
constexpr bool get() const { return a; }
};
int main() {
Debug dbg(true, false, false); // dbg is not a constant
constexpr Debug dbg2(0, 0, 0); // constexpr makes this a constant expression
// *** Begin demo ***
dbg.a = false;
//dbg2.a = false; //< error: assignment of member 'Debug::a' in read-only object
// *** End demo ***
}