我对C++很新,这是我的情况.我有一个参考MyOjbect,但确切的对象取决于条件.所以我想做这样的事情:
MyObject& ref;
if([condition])
ref = MyObject([something])
else
ref = MyObject([something else]);
Run Code Online (Sandbox Code Playgroud)
我现在不能这样做,因为编译器不允许我声明但不初始化引用.我能做些什么来实现我的目标?
请考虑以下代码:
#include <iostream>
#include <type_traits>
template<typename T> class MyClass
{
public:
MyClass() : myVar{0} {;}
void testIf() {
if (isconst) {
myVar;
} else {
myVar = 3;
}
}
void testTernary() {
(isconst) ? (myVar) : (myVar = 3);
}
protected:
static const bool isconst = std::is_const<T>::value;
T myVar;
};
int main()
{
MyClass<double> x;
MyClass<const double> y;
x.testIf();
x.testTernary();
y.testIf(); // <- ERROR
y.testTernary(); // <- ERROR
return 0;
}
Run Code Online (Sandbox Code Playgroud)
对于x(非常量),没有问题.但是,即使在编译时知道if/else中的条件,y(const数据类型)也会导致错误.
是否有可能在编译时不编译错误条件?