Click here to Skip to main content
15,884,388 members
Articles / Programming Languages / C++11

Constants and Constant Expressions in C++11

Rate me:
Please Sign up or sign in to vote.
5.00/5 (12 votes)
11 Jul 2012CPOL8 min read 73.2K   190   24  
keywords: constexpr, constant, constant expression, user-defined literals, GCC 4.7.0
// file: constarray.cpp
#include <iostream>
#include <ostream>

template <class ElemType, int N>
class ConstArray  
{
    const ElemType a[N];
public:    
    template <class ... T> constexpr ConstArray(T ... p):a {p...} {}
    constexpr int size() { return N;}
    constexpr ElemType operator[](int i) 
           { return (i < 0 || i >= N ? throw "ERROR: out of range": a[i]);}    
};

constexpr ConstArray<double, 3> a{1.0, 2.5, 3.0};
constexpr ConstArray<char, 4>s{'a','b','c','d'};

int main()
{    
    try
    {
        std::cout << "a.size(): " << a.size() << std::endl;
        std::cout << "a[2]: " << a[2] << std::endl;
        std::cout << "s[3]: " << s[3] << std::endl;               
        std::cout << "s[4]: " << s[4] << std::endl;               
    }
    catch (const char* error)
    {
        std::cout << error << std::endl;
    }
    return 0;
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions