Solved

template related question

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

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Create a path if not exists 7 108
What is sub-make ? 2 88
Are the two lines the same? If not what is the difference? 2 29
FMX TEdit KeyUp handler detecting  "enter" key 4 41
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…
  Included as part of the C++ Standard Template Library (STL) is a collection of generic containers. Each of these containers serves a different purpose and has different pros and cons. It is often difficult to decide which container to use and …
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

726 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