Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ ';如果';关于C++;模板参数_C++_Templates_Compiler Warnings - Fatal编程技术网

C++ ';如果';关于C++;模板参数

C++ ';如果';关于C++;模板参数,c++,templates,compiler-warnings,C++,Templates,Compiler Warnings,使用英特尔编译器icpc13时,以下代码向我发出警告 #include <iostream> template<int N> class base { public: double x[N]; }; template<int N> class derived : public base<2*N> { public: void print() { if (N=

使用英特尔编译器icpc13时,以下代码向我发出警告

#include <iostream>

template<int N>
class base
{
    public:
        double x[N];
};

template<int N>
class derived : public base<2*N>
{
    public:
        void print()
        {
            if (N==1)
            {
              std::cout << this->x[1] << std::endl;
            }
            else if (N==2)
            {
              std::cout << this->x[3] << std::endl;
            }
        }

};


int main(int argc, char* argv[])
{
    derived<1> temp1;
    derived<2> temp2;

    temp1.print();
    temp2.print();
}
#包括
模板
阶级基础
{
公众:
双x[N];
};
模板
派生类:公共基
{
公众:
作废打印()
{
如果(N==1)
{

std::cout x[1]编译器会检查代码分支,即使它们由于编译时常量而处于非活动状态

ICPC似乎是唯一检查数组边界的,但是您可能会遇到其他恼人的警告,比如VisualC++,当检查N(C4127具有警告级别4)时,它警告恒定的条件表达式。 我一定会注意警告,您的里程可能会有所不同:

  • 使用编译器选项禁用警告
    -wd175
  • 在此特定点禁用与供应商相关的警告
    #pragma警告(禁用:175)
  • 专门化
    derived::print()
    方法并计算出常见代码:
模板
void派生::print()
{

std::cout我很好奇,如果你只是使用:
std::coutUsing,那么你需要检查数组索引是否超出边界。显然,如果N=2,X[3]超出边界,行为未定义。@billz如果派生类中的
N=2
,则它在声明数组的基类中是
4
。它不超出边界。这是
公共基的目的,你说得对。:)这不是一件特别糟糕的事情,但我认为这是对编译器。我会取消警告,并留下评论解释为什么它是安全的。我同意你建议的“修复”。我想知道编译器是否应该检查由于if语句而处于非活动状态的代码块。我想我可以理解为什么会这样,尽管在这种情况下,修复程序会使代码变得非常复杂。ThanksI使用了pragma。我认为您给出的语法可能不受欢迎。我提出了解决方案。您可能是对的,但这两种语法都是正确的ions与icc 13.0.1一起工作,如在上书写时可用
void print()
{
    #ifdef __INTEL_COMPILER
        #pragma warning push
        #pragma warning disable  175
    #endif

    if (N==1)
    {
        std::cout<<this->x[1]<<std::endl;
    }
    else if (N==2)
    {
      std::cout << this->x[3] << std::endl;
    }

    #ifdef __INTEL_COMPILER
        #pragma warning pop
    #endif

    }

};