cpp
cpp

Reputation: 3801

Why using constant expression as a template parameter?

When it is better to have a private data member (_val in class B) and when it is better to have val as a template parameter (class A)?

#include<iostream>
using namespace std;

template<int val>
class A{
public:
        A(){ cout << val << endl;}
};

class B{
public:
        B(int val) : _val(val) { cout << val << endl;}
private:
        int _val;
};

int main()
{
        A<7> a;
        B b(8);
}

Upvotes: 2

Views: 2385

Answers (2)

Michael
Michael

Reputation: 2250

As an end result, the assembly code for Class A would be hard coded, and a separate version of the class would exist for all used integers. A custom class for each constant litteral integer.... in a sense, this is the way to go if you're willing to increase your code size to have execution speed.

Class B constructor would be the same for no matter which integer, and the integer is a run time variable passed in. One constructor, so code size doesn't increase for each different constant integer you use.

Upvotes: 0

TemplateRex
TemplateRex

Reputation: 70556

For class A you can only set or modify val at compile-time, for class B only at run-time. So it depends on when you have enough information to initialize / modify the class. Furthermore, a non-static data member in class B adds a per-object state. Instead you could use a static const int or an enum, which only adds per-class state.

More interestingly, in C++11 you could be using constexpr and initalize both at compile-time and at runtime, depending on the context

class C {
public:
    constexpr C(int val) : _val(val) {}
    constexpr int the_val() { return _val; }
private:
    int _val;
}

int main()
{
    constexpr C c(5);
    A<c.theval()> a;  // uses constexpr to set template parameter at compile-time
    B b(c.theval());  // can be done at compile-time, but not required ("quality of implementation")
}

Upvotes: 4

Related Questions