开发者

Problem for template class<class_name> that has bitset as argument

I want to write a class in C++ in which one of the parameter is a bitset<size>. I want to give the facility to vary this "size" for any object of that class but should be constant for that object.

If I make a variable const int size; and initialize it in the constructor, then it does not compile because to writiting bitset<size> would require size to be static which would make it same for all objects of the class.

Is there any other method than making a class template and passing the size as classname<size>?

thanks but.. but this makes this Foo class objects whenever used as composition开发者_高级运维 (object as data member)... would it be necessary to again make that class template. I made a class and Passed a (#define BIT_SIZE 16 to Foo bits;) it is giving compile errors undefined reference to Foo<16>::Foo(). where Foo() is the constructor. I thought it should work because that is also compile time. and i just wanted to make only size BIT_SIZE bits. should i make my "next level" class template ?? it can be that these errors were because of other mistakes. but i checked that again and again.


yes sir i have implemented that and but included the header files and not cpp files .......... when i changed these to cpp files ... multiple declaration error came. i am working on linux ubuntu .. when i took these files to dev_cpp in windows that worked . may be because compiler did that automatically what i need to do. so what is that i need to do.


Template parameter should be compile time constant; the compiler will generate different classes for different size parameters. If you want to use single bitset class for various possible sizes then use, for instance, Boost dynamic_bitset:

http://www.boost.org/doc/libs/1_47_0/libs/dynamic_bitset/dynamic_bitset.html

and pass the bitset size as constructor parameter


No, there is no other method, because the code for actual instantiation for bitset<N> is generated at compile time, so you have no possibility to delay providing its size until runtime. You have to use the non-type template parameter.

If it was possible, the creators of standard C++ library would have done this and it would be possible to provide the size for bitset at runtime, right?

Using another bit set implementation is an option.


To use the bitset member, you have to make size a template parameter and use that in the member:

template <size_t N>
class Foo
{
  std::bitset<N> thebitset;

public:
  Foo() /* ... */
};

Then to use it, say Foo<12> x;.

In view of your question for alternatives, you could use a runtime-dynamic array instead of a static one:

class Bar
{
  std::vector<unsigned char> thedata;

public:
  explicit Bar(size_t n) : thedata(n, 0) { }

  inline unsigned char & operator[](size_t i) { return thedata[i]; }
  inline const unsigned char & operator[](size_t i) const { return thedata[i]; }
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜