Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

template related question

Posted on 2008-10-10
2
Medium Priority
?
294 Views
Last Modified: 2010-04-16
Hi,
How do you generalize this module to work for any integer value instead of 2?

std::string ToBinString(unsigned long val, int ndigits ){      
      const std::bitset<2> bs(val); //Generalize this - use any integer instead of 2
      const std::string s(bs.to_string());
      return s;
}

Thank you.
0
Comment
Question by:kk8
2 Comments
 
LVL 12

Accepted Solution

by:
trinitrotoluene earned 150 total points
ID: 22689639
Check the following for usage info
http://www.cplusplus.com/doc/tutorial/templates.html
http://www.iis.sinica.edu.tw/~kathy/vcstl/templates.htm


Your code can be rewritten as follows:




template <class T>
 
std::string ToBinString(unsigned long val, int ndigits ){      
      const std::bitset<T> bs(val);
      const std::string s(bs.to_string());
      return s;
}

Open in new window

0
 

Author Comment

by:kk8
ID: 22691054
Thanks for the code. I think you meant

template <size_t T>

instead of

template <class T>

Did not realize i could use size_t as a template, silly me.
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Unlike C#, C++ doesn't have native support for sealing classes (so they cannot be sub-classed). At the cost of a virtual base class pointer it is possible to implement a pseudo sealing mechanism The trick is to virtually inherit from a base class…
Written by John Humphreys C++ Threading and the POSIX Library This article will cover the basic information that you need to know in order to make use of the POSIX threading library available for C and C++ on UNIX and most Linux systems.   [s…
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.
Suggested Courses

971 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question