dimanche 3 janvier 2016

What is the best way to access non-type template parameters from other classes?

I have a container class and other parts of my code need access to its non-type template parameters. You can't access non-type template parameters with the :: operator, so what is be the preferred method of getting at those values?

This minimal code example contains the three methods which I know of:

#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';
}

Compiling with GCC-4.9 (unsurprisingly) gives:

::Size = 42
m_size = 42
size() = 42

All three of these methods work, but is there any difference in performance, or in terms of how well the compiler can optimize code?

In my particular application, the non-type template parameters are frequently used for things like array declarations or arithmetic functions. They are known at compile time, but not at design time. As a result, I want the compiler to make the best use of the information that these values are fixed, but I don't want to hard-code them deep in the source files somewhere, hence the choice of template parameters.

Aucun commentaire:

Enregistrer un commentaire