我有一个容器类,我代码的其他部分需要访问它的非类型模板参数。您不能使用::运算符访问非类型模板参数,那么获取这些值的首选方法是什么?
这个最小的代码示例包含我所知道的三种方法:
#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';
}
用 GCC-4.9 编译(不出所料)给出:
::Size = 42
m_size = 42
size() = 42
所有这三种方法都有效,但在性能或编译器优化代码的能力方面是否存在差异?
在我的特定应用程序中,非类型模板参数经常用于数组声明或算术函数之类的事情。它们在编译时已知,但在设计时未知。因此,我希望编译器充分利用这些值是固定的信息,但我不想在源文件的某个地方对它们进行硬编码,因此选择了模板参数。
最佳答案
解决方案大多是等效的。
enum
是C++03的方式(类型不再是int
)。- constexptr 函数可以在运行时调用(在非 constexpr 上下文中)。
static const
如果地址被占用,需要一个外部定义
不过,我会使用案例 2 的变体:
template<int N>
struct Container
{
static constexpr int m_size = N;
};
关于c++ - 从其他类访问非类型模板参数的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34578795/