相关疑难解决方法(0)

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万
查看次数

编译器:如果条件总是为真/假,该怎么办?

我想到条件和编译器.我正在编写Arduino的应用程序,所以我需要尽可能快的应用程序.

在我的代码中我有这个:

#define DEBUG false    

...

if (DEBUG)
{
  String pinName;
  pinName = "Pin ";
  pinName += pin;
  pinName += " initialized";
  Serial.println(pinName);
}
Run Code Online (Sandbox Code Playgroud)

我想知道编译器是否在二进制文件中不包含代码(if块中的代码).条件总是错误的,所以程序永远不会去那里.

从另一方面来看.如果DEBUG是真的怎么办?Arduino是否测试条件或编译器只包含if在二进制文件中的主体?

我发现这个网站https://gcc.gnu.org/onlinedocs/gcc-3.0.2/cpp_4.html关于#if指令,所以我可以重写代码以获得这些指令而不是"正常"if.但我想知道我是否应该重写它,或者是否浪费时间.

c c++ gcc if-statement arduino

13
推荐指数
1
解决办法
1936
查看次数

标签 统计

c++ ×2

if-statement ×2

arduino ×1

c ×1

compilation ×1

gcc ×1

templates ×1