|
Boost : |
From: Tom Brinkman (reportbase_at_[hidden])
Date: 2005-03-18 23:39:13
How do you specify a string or a double,
or an object as a template parameter?
c++ templates are a compile time construct,
so the answer is that you can't, or at least
not directly.
However, with the use of existing
boost libraries and a little
compiler magic, you can actually specify
a string, double or any object as a template
parameter.
The following code is the proof of
this concept. I would like to gather feedback
from the group and submit this as a boost
utility library if there is sufficient interest.
//TODO
//1) compile the following code as main.cpp.
//2) run the application with
three command line parameters.
#include <vector>
#include <string>
#include <iostream>
#include <boost/variant.hpp>
std::vector<boost::variant<int,
long,double,std::string> > resources;
template <bool>
struct resource{};
template <>
struct resource<false>
{
template <typename INDEX, typename R>
void operator()(INDEX index, R& out)
{
out = oost::get<R>
(resources[index()]);
}
};
template <>
struct resource<true>
{
template <typename T, typename R>
void operator()(T in, R& out)
{
out = in;
}
};
template <typename T, typename R> inline
void get(R& out)
{
resource<boost::is_convertible<
T,R>::value> a;
a(T(),out);
}
template <int T=-1>
struct resource_wrapper
{
static const int value = T;
int operator()(){return T;}
};
template <int T=0>
struct integer
{
static const int value = T;
operator int(){return T;}
};
typedef resource_wrapper<1> str1;
typedef resource_wrapper<2> str2;
typedef resource_wrapper<3> str3;
typedef resource_wrapper<4> columns;
template <typename STRING>
struct funct
{
void operator()()
{
std::string str;
get<STRING>(str);
std::cout << str << std::endl;
}
};
template <typename DOUBLE>
struct funct2
{
void operator()()
{
double dbl;
get<DOUBLE>(dbl);
std::cout << dbl << std::endl;
}
};
int main(int argc, char* argv[])
{
resources.resize(100);
resources[str1::value] =
std::string(argv[1]);
resources[str2::value] =
std::string(argv[2]);
resources[str3::value] =
std::string(argv[3]);
resources[columns::value] = 6.33;
funct<str1>()();
funct<str2>()();
funct<str3>()();
funct2<columns>()();
funct2<integer<10> >()();
return 0;
}
__________________________________________________
Do You Yahoo!?
Tired of spam? Yahoo! Mail has the best spam protection around
http://mail.yahoo.com
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk