Afficher un message
Vieux 13/04/2008, 14h39   #5
Pascal Bourguignon
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: initialiser variable constante dans le constructeur

James Kanze <james.kanze@gmail.com> writes:
> Fabien a montré la solution classique, mais il faut signaler que
> s'il s'agit de plusieurs valeurs, dans une seule chaîne de
> caractères, la solution est loin d'être optimale, parce qu'il
> faudrait récréer la istringstream pour chaque valeur, sautant
> les valeurs qu'on ne recherche pas chaque fois.


Quel manque d'imagination!

#include <ciso646>
#include <map>
#include <string>
#include <vector>
#include <sstream>
#include <iostream>
#include <iterator>
#include <exception>

class Error:public std::exception {
std::string message;
public:
Error(std::string const& aMessage):message(aMessage){};
~Error(void)throw(){};
const char* what(void){return(message.c_str());}
};

class C
{
public:
C(std::string const&);
inline int getA(void) const {return a;}
inline int getB(void) const {return b;}
private:
int const a;
int const b;
int getParameter(std::string const& arguments,unsigned int n);
};

C::C(std::string const& param)
: a(getParameter(param,1)),
b(getParameter(param,2))
{}


int C::getParameter(std::string const& arguments,unsigned int n){
typedef std::map<std::string,std::vector<int> > ParameterCache;
static ParameterCache cache;
ParameterCache::iterator parameters=cache.find(arguments);
if(parameters==cache.end()){
std::istringstream in(arguments);
std::vector<int> parsedArgs;
while(not(in.eof())){
int argument;
in>>argument;
parsedArgs.push_back(argument);
}
cache[arguments]=parsedArgs;
parameters=cache.find(arguments);
}
if(parameters->second.size()<=n){
throw Error("Too few arguments");
}
return(parameters->second[n]);
}

int main(void){
C c0("0 1 2 3");
C c1("10 11 12 13");
std::cout<<"c0: "<<c0.getA()<<" "<<c0.getB()<<std::endl;
std::cout<<"c1: "<<c1.getA()<<" "<<c1.getB()<<std::endl;
return(0);
}

/*
-*- mode: compilation; default-directory: "~/src/miscellaneous/tests-c++/" -*-
Compilation started at Sun Apr 13 15:38:52

g++ -o const-member const-member.c++ && ./const-member
c0: 1 2
c1: 11 12

Compilation finished at Sun Apr 13 15:38:57
*/


--
__Pascal Bourguignon__ http://www.informatimago.com/

NEW GRAND UNIFIED THEORY DISCLAIMER: The manufacturer may
technically be entitled to claim that this product is
ten-dimensional. However, the consumer is reminded that this
confers no legal rights above and beyond those applicable to
three-dimensional objects, since the seven new dimensions are
"rolled up" into such a small "area" that they cannot be
detected.
  Réponse avec citation
 
Page generated in 0,06948 seconds with 9 queries