0

The compiler complains at the following code snippet, it says that cx isn't a constant expression. And since cx isn't constant, it is invalid to pass it in as a template argument of the function T(). However, isn't getFoo() a const function? Thus isn't x const and hence cx const? And even if x is not, isn't cx forced to be const with the const identifier?

What should I do to make cx const and be successfully passed as a valid template argument of T()?



    //M is an instance of class C
    unsigned int x = M.getFoo(); //isn't this supposedly be constant?
    const unsigned int cx = x;
    C<cx> Mt = M.T<cx>();


Calling the following 2 public member function of class C:



    const int getFoo() const{    
        return foo; //a private variable which value is set in the constructor 
    }




    <template unsigned int ROWS>
    const C<ROWS> T() const{
        //after some declarations and computations...
        return Ct;
    }


too honest for this site
  • 12,050
  • 4
  • 30
  • 52
Clueless Gorilla
  • 1,199
  • 2
  • 10
  • 16
  • 3
    `const` and "compile time const" are not always the same thing. Look into `constexpr`. – Niall Jul 28 '15 at 20:58
  • Elaborate please? Thanks! It seems the constexpr is a c++11 specific expression – Clueless Gorilla Jul 28 '15 at 21:00
  • 2
    `const` just means it can't change once set (it could be set at runtime). `constexpr` can be used to give you a compile time constant if possible - basically it tells the compiler to calculate the answer if the arguments are also `constexpr`. So in your example it would mean that `getFoo` and the constructor would need to be `constexpr`. If the compiler can, it will calculate the answer for you - the rules here are many, so you'll need to play with the code and see if it works. – Niall Jul 28 '15 at 21:04
  • 2
    C++ is **not** C is **not** C++! That is C++, not C! (Do not add a tag, just because it starts with the same letter as your language) – too honest for this site Jul 28 '15 at 21:04
  • Your answer to your question is a subset of the answers you'll find at http://stackoverflow.com/questions/14116003/difference-between-constexpr-and-const. – R Sahu Jul 28 '15 at 22:11

0 Answers0