Re: How: Interfacing two template methods?
On Jul 5, 9:58 am, t.lehm...@rtsgroup.net wrote:
- - -
template <classT>
bool setValue(unsigned int key, const T& value);
- - -
I think you are placing the template in the wrong spot for what you
are trying to do. Either 1) the value will be cast to something, or
2) something type-specific must be done with it. If there is a cast,
you don't need a template. If it's something type-specific, it still
needs to be converted to something common to all types. For example:
std::cout takes a lot of types, but all are converted to text data.
If this is the case (all values are converted to a common type based
on their type,) that should be handled by an overloaded function and
the "common data" should be the second argument. That will allow you
to eliminate the template for the functionality which is variable, and
the functionality which isn't variable (any conversion steps) may be
templates since they won't be dynamic.
#include <string>
#include <sstream>
#include <iostream>
//template conversion function
template <class Type>
std::string convert(Type vValue)
{
std::ostringstream temp_stream;
temp_stream << vValue;
return temp_stream.str();
}
//base class
struct attributor
{
virtual bool set_value(int, const std::string&) = 0;
};
//derived classes
struct display_only : public attributor
{
bool set_value(int kKey, const std::string &vValue)
{
std::cout << kKey << ": " << vValue << " (displayer)\n";
return true;
}
};
struct assign_value : public attributor
{
bool set_value(int kKey, const std::string &vValue)
{
key = kKey;
value = vValue;
return true;
}
int key;
std::string value;
};
//template value-setting function
template <class Type>
bool set_value(attributor &aAttributor, int kKey, const Type &vValue)
{ return aAttributor.set_value(kKey, convert(vValue)); }
//main function
int main()
{
display_only displayer;
assign_value assigner;
set_value(displayer, 1, 100);
set_value(displayer, 2, "hello");
set_value(assigner, 3, -200);
std::cout << assigner.key << ": " << assigner.value << " (assigner)
\n";
set_value(assigner, 4, "good bye");
std::cout << assigner.key << ": " << assigner.value << " (assigner)
\n";
}
Kevin P. Barry
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]