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

标签 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++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/

相关文章:

javascript - 使用模板但保留 jquery 绑定(bind)?

c++ - 本地类的限定名称

c++ - 依赖非类型参数包 : what does the standard say?

templates - 错误 : "invalid type for comparison" in revel template

C++ - 在范围内生成遵循正态分布的随机数

c++ - c++-try block 之后是否需要立即编写catch block ?

C++ 随机数生成器只输出 2

c++ - QDataStream 有时使用 32 位 float ,有时使用 40 位 float

c++ - 没有卡尔曼滤波器的 BackgroundSubtractorGMG?

c++ - 使用非 MSVC 编译器在 Windows 下打开带有 Unicode 文件名的文件的 fstream