相关疑难解决方法(0)

如何声明引用并在以后初始化

我对C++很新,这是我的情况.我有一个参考MyOjbect,但确切的对象取决于条件.所以我想做这样的事情:

MyObject& ref; 
if([condition]) 
  ref = MyObject([something]) 
else 
  ref = MyObject([something else]);
Run Code Online (Sandbox Code Playgroud)

我现在不能这样做,因为编译器不允许我声明但不初始化引用.我能做些什么来实现我的目标?

c++ reference

52
推荐指数
7
解决办法
6万
查看次数

if/else在C++的编译时?

请考虑以下代码:

#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数据类型)也会导致错误.

是否有可能在编译时不编译错误条件?

c++ templates if-statement compilation

14
推荐指数
3
解决办法
2万
查看次数

标签 统计

c++ ×2

compilation ×1

if-statement ×1

reference ×1

templates ×1