繁体   English   中英

Constexpr作为模板函数中的数组大小(GCC与Intel)

[英]Constexpr as Array Size in Template Function (GCC vs Intel)

我正在研究用C ++ 11编写的科学代码。 此代码的关键操作在3D阵列上执行。 这样的数组也经常传递给其他函数。 在实现一些新功能时,我使用了模板并遇到以下问题:该代码在gcc 5.4(也经过测试7.2)下可以正常编译,但是在Intel C ++编译器ICC 16.0(也经过测试18.0)下无法编译,所以我不知道我的代码是否可以编译。代码不符合标准,或者这些编译器之一行为异常。

最小的示例代码如下(实际上是3D数组):

class Constants {   
   static constexpr int value_ = 2;

public:    
   static constexpr inline int V() { return value_; }    
};

typedef Constants CC;

template<int N>
class Terror {    
public:
  template<class T>
  void F(T (&a)[CC::V()]) {}
};

int main() {
  int array[CC::V()];    
  Terror<42> ter = Terror<42>();    
  ter.F(array);
}

我知道传递(3D)普通C数组(通过constexpr确定大小)不是经典方法,但是有很多原因可以根据需要对此进行详细说明。

我尝试阅读C ++ 11标准,但没有找到(至少对我来说)问题的清晰说明。

ICC引发的错误是这样的:

main.cpp(15): error: no instance of function template "Terror<N>::F [with N=42]" matches the argument list
            argument types are: (int [2])
            object type is: Terror<42>
   ter.F(array); 
       ^
template_class.h(10): note: this candidate was rejected because at least one template argument could not be deduced
    void F(T (&a)[CC::V()]) {}
         ^

compilation aborted for main.cpp (code 2)

有趣的是,它可以与(3D-)std :: array一起使用,或者如果不存在N / T的两个模板之一,则可以使用它。

这是一个ICC错误。

值得庆幸的是,有一个非常简单的解决方法,即将该值存储在Terror

template<int N>
class Terror {    
    static constexpr size_t M = CC::V();
public:
    template<class T>
    void F(T (&a)[M]) {}
};

ICC 16和17都接受了此更改的程序。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM