Solved

template related question

Posted on 2008-10-10
2
234 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
Comment Utility
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
Comment Utility
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 Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

In days of old, returning something by value from a function in C++ was necessarily avoided because it would, invariably, involve one or even two copies of the object being created and potentially costly calls to a copy-constructor and destructor. A…
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 viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

743 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

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now