Solved

template related question

Posted on 2008-10-10
2
257 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 50 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

What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

Question has a verified solution.

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

Errors will happen. It is a fact of life for the programmer. How and when errors are detected have a great impact on quality and cost of a product. It is better to detect errors at compile time, when possible and practical. Errors that make their wa…
Many modern programming languages support the concept of a property -- a class member that combines characteristics of both a data member and a method.  These are sometimes called "smart fields" because you can add logic that is applied automaticall…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…

770 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