0

Suppose I have following template class:

template<unsigned char I, unsigned char F>
class FOO
{
  ....
}

In the main function, I have many such variables, with different (I, F), like following,

int main()
{
   .....
   FOO<4, 2> a;
   FOO<6, 3> b;
   ......
}

I want to retain the value of I or F for the defined variables in my main function. Of course, I can define a public/private members for FOO and save the value of (I, F) inside the FOO's constructor, like

template<I,F>
FOO<I,F>::FOO(){
   i = I;
   f = F;
}

Disadvantage of this method is obvious: It enlarge the size of the FOO. IMO, (I, F) of any variable can be determined at compiling time, so there should be a way to do this without creating local variable.

2
  • What about static const members in the template class? static const unsigned char my_I = I; Or via any kind of function in the class, static or non-static. If you think that won't work for you, I'm afraid you'll have to say how you actually plan to use the values.
    – pmdj
    Mar 3, 2012 at 17:20
  • 1
    I'm not sure I understand the problem. You can use I or F anywhere inside your class template. Mar 3, 2012 at 17:20

3 Answers 3

2

The usual way (like std::array in C++11) is to do the following:

constexpr unsigned char i() const { return I; }
constexpr unsigned char f() const { return F; }

If your compiler doesn't support constexpr, remove it.

2

Within your class definition, you can simply refer to the parameters literally (just like any other template parameters!).

But suppose you have this:

typedef Foo<10, 20> MyFoo;

MyFoo x;   // what is I, what is K?

The customary thing is to reflect the template parameters inside the class definition:

template <int A, typename T> struct Foo
{
    static int const a_value = A;
    typedef T               type;
    // ...
};

Now you can say: MyFoo::type x; return MyFoo::a_value; etc. Note that integral static class constants don't usually need a definition unless you do something like take their address, so in most cases this won't have any cost in the compiled code -- the compiler simply substitutes the value whenever it sees the name of the constant.

1

you can simply use the template parameters, like this:

#include <iostream>

using namespace std;

template<unsigned char I, unsigned char F>
class FOO
{
public:
    void bar() {
        cout << "I is: "<<I<<endl;
    }
    char getI() {
        return I;
    }
};

using namespace std;
int main(){
    FOO<4,2> a;
    a.bar();
    cout << "getI:"<<a.getI()<<endl;
}

you don't need a copy, as in your example (i = I)

BTW: fully capitalized names like FOO are usually by convention reserved for preprocessor Macros.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.