Hello, I've made a templated class Option (a child of the abstract base
class OptionBase) that stores an option name (in the form someoption=) and
the value belonging to that option. The value is of the type the object is
instantiated with. In my test program I have Option<std::str ing> and
Option<long>. Here's the code for OptionBase and Option along with a small
helper function. In the code are comments describing my problem, look
closely at the read_option() and convert() functions in the Option class.
#ifndef OPTION_HPP
#define OPTION_HPP
#include <stdexcept>
#include <string>
#include <typeinfo>
static bool
starts_with(con st std::string& s, const std::string& starts_with)
{
if(s.length() < starts_with.len gth())
return false;
std::string str = s.substr(0, starts_with.len gth());
if(str == starts_with)
return true;
return false;
}
class OptionBase
{
public:
OptionBase(cons t std::string& name)
:
m_name(name),
m_not_set(true) {}
virtual ~OptionBase() {}
virtual void read_option(con st std::string&) = 0;
const std::string get_name() const
{
return m_name;
}
protected:
std::string m_name;
bool m_not_set;
};
template<typena me T>
class Option : public OptionBase
{
public:
Option(const std::string& name)
:
OptionBase(name ) {}
virtual void read_option(con st std::string& s)
{
if(!starts_with (s, m_name))
throw std::runtime_er ror(std::string ("Didn't find option ") +
m_name);
std::string str = s.substr(m_name .length(), s.length());
if(str.empty())
throw std::runtime_er ror("Option lacks value.");
/* Problem: Will try to convert std::string to std::string
which will lead to "Iron Gual Dye" becoming just "Iron". */
T tmp = convert(str);
set_value(tmp);
}
T get_value() const
{
if(m_not_set)
throw std::runtime_er ror("Called get_value() when no value had been
set.");
return m_value;
}
void set_value(const T& value)
{
m_value = value;
m_not_set = false;
}
private:
T convert(const std::string& s)
{
/* Here I want to simply return s if(typeid(T) == typeid(std::str ing)
but return (T)s doesn't compile when this class is instantiated
with type long (I'm using long and std::string in my test program).
*/
stringstream ss;
ss << s;
T out;
if(!(ss >> out))
throw runtime_error(" Conversion not possible.");
return out;
}
T m_value;
};
#endif /* #ifndef OPTION_HPP */
So the problem is convert(). When I have instantiated my object with
std::string and I call read_option() on that object it will call convert()
and convert() will convert a string containing spaces to a substring up to
the first space. Iron Gual Dye becomes Iron for example. How should I
prevent this from happening? If I have instantiated with std::string I don't
want to call convert (because it messes up strings with spaces) but I have
to because of set_value().
Hope you understand what I mean...I can provide a complete and compilable
example exhibiting the problem should anyone want me to.
/ Eric 4 3632
Eric Lilja wrote: template<typena me T> class Option : public OptionBase { public: Option(const std::string& name) : OptionBase(name ) {}
virtual void read_option(con st std::string& s) {
[snip]
/* Problem: Will try to convert std::string to std::string which will lead to "Iron Gual Dye" becoming just "Iron". */ T tmp = convert(str);
set_value(tmp); }
[snip]
private: T convert(const std::string& s) { /* Here I want to simply return s if(typeid(T) ==
typeid(std::str ing) but return (T)s doesn't compile when this class is
instantiated with type long (I'm using long and std::string in my test
program). */
stringstream ss; ss << s;
T out;
if(!(ss >> out)) throw runtime_error(" Conversion not possible.");
return out; }
T m_value; };
#endif /* #ifndef OPTION_HPP */
So the problem is convert(). When I have instantiated my object with std::string and I call read_option() on that object it will call
convert() and convert() will convert a string containing spaces to a substring
up to the first space. Iron Gual Dye becomes Iron for example. How should I
prevent this from happening? If I have instantiated with std::string
I don't want to call convert (because it messes up strings with spaces) but I
have to because of set_value().
Hope you understand what I mean...I can provide a complete and
compilable example exhibiting the problem should anyone want me to.
/ Eric
You can create a specialization for Option<std::str ing> that does not
read from the string stream.
Hope this helps,
-shez-
"Shezan Baig" wrote: Eric Lilja wrote: template<typena me T> class Option : public OptionBase { public: Option(const std::string& name) : OptionBase(name ) {}
virtual void read_option(con st std::string& s) {
[snip]
/* Problem: Will try to convert std::string to std::string which will lead to "Iron Gual Dye" becoming just "Iron". */ T tmp = convert(str);
set_value(tmp); }
[snip]
private: T convert(const std::string& s) { /* Here I want to simply return s if(typeid(T) == typeid(std::str ing) but return (T)s doesn't compile when this class is instantiated with type long (I'm using long and std::string in my test program). */
stringstream ss; ss << s;
T out;
if(!(ss >> out)) throw runtime_error(" Conversion not possible.");
return out; }
T m_value; };
#endif /* #ifndef OPTION_HPP */
So the problem is convert(). When I have instantiated my object with std::string and I call read_option() on that object it will call convert() and convert() will convert a string containing spaces to a substring up to the first space. Iron Gual Dye becomes Iron for example. How should I
prevent this from happening? If I have instantiated with std::string I don't want to call convert (because it messes up strings with spaces) but I have to because of set_value().
Hope you understand what I mean...I can provide a complete and compilable example exhibiting the problem should anyone want me to.
/ Eric
You can create a specialization for Option<std::str ing> that does not read from the string stream.
Hope this helps, -shez-
Thanks for your reply. I tried moving the convert() function outside the
class and made a specialization for it for std::string but it always calls
the "wrong" convert. The code:
template<typena me T>
T convert(const std::string& s, T)
{
stringstream ss;
ss << s;
T out;
if(!(ss >> out))
throw runtime_error(" Conversion not possible.");
return out;
}
template<typena me T>
std::string convert(const std::string& s, std::string)
{
return s;
}
But maybe that's not what you meant? My template skills are a bit weak I
must say =/
/ Eric
"Eric Lilja" wrote: "Shezan Baig" wrote: Eric Lilja wrote: template<typena me T> class Option : public OptionBase { public: Option(const std::string& name) : OptionBase(name ) {}
virtual void read_option(con st std::string& s) {
[snip]
/* Problem: Will try to convert std::string to std::string which will lead to "Iron Gual Dye" becoming just "Iron". */ T tmp = convert(str);
set_value(tmp); }
[snip]
private: T convert(const std::string& s) { /* Here I want to simply return s if(typeid(T) == typeid(std::str ing) but return (T)s doesn't compile when this class is instantiated with type long (I'm using long and std::string in my test program). */
stringstream ss; ss << s;
T out;
if(!(ss >> out)) throw runtime_error(" Conversion not possible.");
return out; }
T m_value; };
#endif /* #ifndef OPTION_HPP */
So the problem is convert(). When I have instantiated my object with std::string and I call read_option() on that object it will call convert() and convert() will convert a string containing spaces to a substring up to the first space. Iron Gual Dye becomes Iron for example. How should I
prevent this from happening? If I have instantiated with std::string I don't want to call convert (because it messes up strings with spaces) but I have to because of set_value().
Hope you understand what I mean...I can provide a complete and compilable example exhibiting the problem should anyone want me to.
/ Eric
You can create a specialization for Option<std::str ing> that does not read from the string stream.
Hope this helps, -shez-
Thanks for your reply. I tried moving the convert() function outside the class and made a specialization for it for std::string but it always calls the "wrong" convert. The code: template<typena me T> T convert(const std::string& s, T) { stringstream ss; ss << s;
T out;
if(!(ss >> out)) throw runtime_error(" Conversion not possible.");
return out; }
template<typena me T> std::string convert(const std::string& s, std::string) { return s; }
But maybe that's not what you meant? My template skills are a bit weak I must say =/
/ Eric
I solved it, here it is with the convert() function as a stand-alone
function:
template<typena me T1, typename T2>
T2 convert(const T1& a, const T2&)
{
stringstream ss;
ss << a;
T2 out;
if(!(ss >> out))
throw runtime_error(" Conversion not possible.");
return out;
}
template<>
std::string convert(const std::string& s, const std::string&)
{
return s;
}
Now, should I (can I?) make convert a member of the class Option? And can I
loose the second argument (it's after all not used in the function)?
/ Eric
Eric Lilja wrote: I solved it, here it is with the convert() function as a stand-alone function: template<typena me T1, typename T2> T2 convert(const T1& a, const T2&) { stringstream ss; ss << a;
T2 out;
if(!(ss >> out)) throw runtime_error(" Conversion not possible.");
return out; }
template<> std::string convert(const std::string& s, const std::string&) { return s; }
Now, should I (can I?) make convert a member of the class Option? And
can I loose the second argument (it's after all not used in the function)?
/ Eric
You don't need to second argument. In the option class, declare it
like this:
template<typena me RETURN_TYPE>
RETURN_TYPE convert(const std::string& s);
Outside the class, provide two definitions for this function, one
generic and the other specialized for std::string:
template <typename TYPE>
template <typename RETURN_TYPE>
RETURN_TYPE Option<TYPE>::c onvert(const std::string& s)
{
// ...
}
template <typename TYPE>
template <>
std::string Option<TYPE>::c onvert<std::str ing>(const std::string& s)
{
// ...
}
When you call the convert function, you call it like this:
convert<TYPE>(s );
So, if 'TYPE' is 'std::string', it will call the specialised version.
Hope this helps,
-shez- This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Arvid Andersson |
last post by:
Hello, I need to convert a string to a number, but the string can
contain +,-,* and / as well as parenthesis. For example, if I have the
string "30/(6+9)" I would like a function that returned the number 2.
I actually wrote a java function that did this a couple of years ago, in
school, as an excersise in "binary trees". I lost it, and most of my
programming knowledge, but I figured perhaps there is a way to do this
easily in python? It...
|
by: Dave |
last post by:
Hello all,
Quoting from page 24 of "The Boost Graph Library; User Guide and Reference
Manual":
"It turns out that by the contravariance subtyping rule, the parameter type
in the derived classes member function must be either the same type or a
base class of the type as the parameter in the base class."
Now please consider this code:
|
by: Gerry Abbott |
last post by:
Hi All,
Im trying to use thie combination but have not had success. Below is the
function
It tried the following
myriskLevel(2,2)
myrisklevel(0,0,2)
and the ismissing(Three) alwasy returns false.?
|
by: Edward Diener |
last post by:
In C++ an overridden virtual function in a derived class must have the exact
same signature of the function which is overridden in the base class, except
for the return type which may return a pointer or reference to a derived
type of the base class's return type.
In .NET the overridden virtual function is similar, but an actual parameter
of the function can be a derived reference from the base class's reference
also.
This dichotomy...
|
by: Ian Bicking |
last post by:
I got a puzzler for y'all. I want to allow the editing of functions
in-place. I won't go into the reason (it's for HTConsole --
http://blog.ianbicking.org/introducing-htconsole.html), except that I
really want to edit it all in-process and in-memory. So I want the
identity of the function to remain the same, even as I edit the body
and hopefully the signature too.
Well, the reason is that I want to edit any function object, without...
| |
by: mosesdinakaran |
last post by:
Hi everybody,
Today I faced a problem where I am very confused and I could not
solve it and I am posting here....
My question is
Is is possible to return a value to a particular function
The question may be silly or even meaning less but
please............
|
by: FAQ server |
last post by:
-----------------------------------------------------------------------
FAQ Topic - Why does 1+1 equal 11? or How do I convert a string to a number?
-----------------------------------------------------------------------
Javascript variables are loosely typed: the conversion between a
string and a number happens automatically. Since plus (+) is also
used as in string concatenation, « '1' + 1 » is equal to « '11' »: the
String deciding...
|
by: Robert Dufour |
last post by:
I am trying to sort the membership list of the membership provider for
ASP.NET
the code has retrieved the list and now we need to sort it by a parameter if
it was passed. So in C# the code is.
Comparison<MembershipUserWrappercomparer = null;
switch (sortDataBase)
{
|
by: FAQ server |
last post by:
-----------------------------------------------------------------------
FAQ Topic - Why does 1+1 equal 11? or How do I convert a
string to a number?
-----------------------------------------------------------------------
Javascript variables are loosely typed: the conversion between a
string and a number happens automatically. Since plus (+) is also
used as in string concatenation, ` '1' + 1 ` is equal to ` '11' `: the
String deciding...
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
| |
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |