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++_Templates_C++11_C++14 - Fatal编程技术网

C++ 从其他类访问非类型模板参数的最佳方法是什么?

C++ 从其他类访问非类型模板参数的最佳方法是什么?,c++,templates,c++11,c++14,C++,Templates,C++11,C++14,我有一个容器类,代码的其他部分需要访问它的非类型模板参数。您不能使用::运算符访问非类型模板参数,那么获取这些值的首选方法是什么 这个最小的代码示例包含我所知道的三种方法: #include <iostream> template<int N> struct Container { enum{Size = N}; static const int m_size = N; constexpr int size() {return N;} //c+

我有一个容器类,代码的其他部分需要访问它的非类型模板参数。您不能使用::运算符访问非类型模板参数,那么获取这些值的首选方法是什么

这个最小的代码示例包含我所知道的三种方法:

#include <iostream>

template<int N>
struct Container 
{
    enum{Size = N};
    static const int m_size = N;
    constexpr int size() {return N;} //c++11
}; 

int main() {
    Container<42> c;

    //Output all three methods of getting N
    std::cout<< "::Size = " << Container<42>::Size << '\n';
    std::cout<< "m_size = " << c.m_size << '\n';
    std::cout<< "size() = " << c.size() << '\n';
}
这三种方法都可以工作,但是在性能上,或者在编译器优化代码的能力方面,有什么不同吗


在我的特定应用程序中,非类型模板参数经常用于数组声明或算术函数。它们在编译时已知,但在设计时不知道。因此,我希望编译器最好地利用这些值是固定的信息,但我不想在源文件的某个地方对它们进行硬编码,因此需要选择模板参数。

这里根本不考虑性能。您可以对其进行度量,但这三个程序的编译都是相同的,这一点很简单

就风格而言,我更喜欢
static const int
成员。不过,这完全取决于你。追求设计的一致性。

解决方案基本上是等效的

  • enum
    是C++03方式(其类型不再是
    int
  • 可以在运行时调用constexptr函数(在非constexpr上下文中)
  • static const
    如果采用地址,则需要外部定义
不过,我会使用案例2的变体:

template<int N>
struct Container 
{
    static constexpr int m_size = N;
}; 
模板
结构容器
{
静态constexpr int m_size=N;
}; 

m_size
在表达式中是左值,但您尚未提供定义(类外)。因此,您无法将其绑定到引用,或以任何其他方式odr使用它。@dyp因此对于
静态常量int
而言,类外定义和类内定义之间存在差异?我知道对于
double
而言,只有
constepr
是有效的,但是
静态constepr int
静态constepr int
之间有语义上的区别吗?@Manik:
constepr
不需要外部定义。@Jarod42没有,就像
const
一样。
template<int N>
struct Container 
{
    static constexpr int m_size = N;
};