I originally had a problem creating a map of classes, with some help
I realized I actually need a map<string, unique_ptr<myclass>>.
To be more precise:
I have a bunch of specialized classes with a common ancestor.
specialized classes are actually specialized from the same template.
I have a std::map<std::string, unique_ptr<ancestor>> taking ownership
of my instances (I hope).
I need ownership because the function creating the instances is in a
completely different section of code than the place using them.
If useful: I create the map at initialization time and then I only
reference it at runtime; for all practical purposes after initializing
it (a complex affair, involving reading config files) it could become
const.
A minimal example of what I need to achieve is:
#include <iostream>
#include <string>
#include <memory>
#include <map>
class generic {
std::string _name;
public:
generic(std::string name) : _name(name) {}
virtual ~generic() = default;
virtual std::string name() { return _name; }
virtual std::string value() { return "no value in generic"; }
};
template <class T> class special : public generic {
T _value;
public:
special(std::string name, T value) : generic(name), _value(value) {}
virtual ~special() = default;
std::string value() override { return std::to_string(_value); }
};
template <typename T> void add_item(std::map <std::string, std::unique_ptr<generic>> &m, const std::string &n, const T &v) {
m[n] = std::make_unique<special<T>>(typeid(v).name(), v);
}
int
main() {
std::map <std::string, std::unique_ptr<generic>> instances;
add_item<int>(instances, "int", 1);
add_item<bool>(instances, "bool", true);
add_item<float>(instances, "float", 3.1415);
for (auto i : instances) {
std::cout << i.first << " -- " << i.second.get()->name() << " -- " << i.second.get()->value() << std::endl;
}
return 0;
}
Unfortunately I seem to be missing something because compilation bombs with "error: use of deleted function".
Can someone be so kind to help me sort this out?
In this loop you try to copy unique_ptrs, but the unique_ptr copy constructor is deleted.
for (auto i : instances) {
You need to take them by reference instead:
for (auto& i : instances) {
Related
I have an algorithm (not preseted here) which takes as input different parameters (int, float, vectors).
My idea of design was to have an container which holds all these differents parameters.
To achive this, I have a base class Parameter and a derivated template class TypeParameter.
These parameters will be holded in a container.
The design is presented below:
#pragma once
#include <utility>
#include <memory>
#include <string>
#include <vector>
namespace parameter
{
/*
Interface for parameter
*/
class Parameter
{
public:
Parameter() {}
Parameter(std::string param_name) : name(param_name) {}
Parameter(const Parameter&& other) noexcept : name(std::move(other.name)) {}
virtual ~Parameter() {}
inline const std::string get_name() { return name; }
private:
std::string name;
};
/*
*/
template<class T>
class TypeParameter
: public Parameter
{
public:
TypeParameter(std::string param_name, T new_value) : Parameter(param_name), value(new_value) {}
TypeParameter(const TypeParameter&& other) noexcept : Parameter(std::move(other)), value(std::move(other.T)) {}
inline const T get_value() { return value; }
private:
T value;
};
/*
Container for parameters
*/
class ParameterSet
{
public:
ParameterSet() {}
void add(std::unique_ptr<Parameter> param) { data.push_back(std::move(param)); }
private:
std::vector <std::unique_ptr<Parameter>> data;
};
} //namespace parameter
The main is:
#include <iostream>
#include <string>
#include "Parameter.h"
using parameter::TypeParameter;
using parameter::Parameter;
using parameter::ParameterSet;
void foo(std::unique_ptr<Parameter> p)
{
std::cout << p->get_value(); // ERROR
}
int main(int argc, char *argv[])
{
TypeParameter<int> *iparam = new TypeParameter<int>("ee", 3);
std::unique_ptr<Parameter> p = std::make_unique <TypeParameter<int>>("foo", 3);
foo(std::move(p));
ParameterSet param_set;
param_set.add(std::unique_ptr<Parameter>(iparam));
param_set.add(std::move(p));
getchar();
}
My problem is I cannot get the value without a cast.
Hence, my question is how do I cast the unique_ptr from a Parameter class to derived TypeParameter.
Is there another way to design the container?
Thanks a lot!
You don't have to reinvent the wheel. There are a couple of classes you can use from the standard library:
std::variant.
As suggested by the comments, variant is a type-safe union of a pre-defined set of data types, which you put in the templates argument of variant.
For example, a std::variant<int,float,double> can hold any value of type int, float, or double, but nothing else.
To use the stored value, you can either use the visitor pattern with the std::visit() function. Other functions allow you to know which of the preset types is stored in the variable (index()) and to extract the value from it (using get()). If you try to extract the value of the wrong type, the get() function throws an exception
std::any
is another utility that can hold different data types. As opposed to variant, you don't have to know the types at compile-time. Basically, it stores a void* to the data with a typeinfo to remember its original type. You can then use any_cast to cast the variable back to its original type. Just like variant, an exception is thrown when trying to cast to the wrong type.
These two classes are available in C++ 17. If these features are not available to you, they were also included in boost (respectively boost:variant and boost:any)
You can store the set of values in a standard library container, e.g. in a std::vector<std::variant<int,float,double>> or a std::vector<std::any>>.
Alternative to std::variant/std::any is the old way polymorphism:
class Parameter
{
public:
Parameter(const std::string& param_name) : name(param_name) {}
virtual ~Parameter() = default;
const std::string& get_name() const { return name; }
virtual void printValue() const = 0;
// Other virtual methods
private:
std::string name;
};
template<class T>
class TypeParameter : public Parameter
{
public:
TypeParameter(const std::string& name, const T& t) : Parameter(name), value(t) {}
// Non virtual method when we don't access it by base class.
const T& get_value() const { return value; }
void printValue() const { std::cout << value; }
private:
T value;
};
And then your
void foo(const Parameter& p)
{
std::cout << p.get_value(); // ERROR
}
becomes
void foo(const Parameter& p)
{
p.print();
}
If you don't want to add many virtual methods to Parameter, then Visitor pattern can help, but then you have to know each derived types.
In my project there are a lot of strings with different meanings at the same scope, like:
std::string function_name = "name";
std::string hash = "0x123456";
std::string flag = "--configure";
I want to distinguish different strings by their meaning, to use with function overloads:
void Process(const std::string& string_type1);
void Process(const std::string& string_type2);
Obviously, I have to use different types:
void Process(const StringType1& string);
void Process(const StringType2& string);
But how to implement those types in an elegant manner? All I can come with is this:
class StringType1 {
std::string str_;
public:
explicit StringType1(const std::string& str) : str_(str) {}
std::string& toString() { return str_; }
};
// Same thing with StringType2, etc.
Can you advise more convenient way?
There is no point in renaming functions since the main goal is to not mistakenly pass one string type instead of another:
void ProcessType1(const std::string str);
void ProcessType2(const std::string str);
std::string str1, str2, str3;
// What should I pass where?..
You probably want a template with a tag parameter:
template<class Tag>
struct MyString
{
std::string data;
};
struct FunctionName;
MyString<FunctionName> function_name;
Simple approach:
struct flag {
string value;
};
struct name {
string value;
};
You could improve this with implicit conversions to strings or other memberfunctions, too.
You could use a similar technique as I applied to std::vector in this answer.
Here's how it would look like for std::string:
#include <iostream>
#include <string>
template<typename Tag, class T>
struct allocator_wrapper : T
{ using T::T; };
template< typename Tag,
typename CharT = char,
typename Traits = std::char_traits<CharT>,
typename Allocator = std::allocator<CharT> >
using MyString = std::basic_string<CharT,Traits,allocator_wrapper<Tag, Allocator>>;
class HashTag;
class FlagsTag;
using Hash = MyString<HashTag>;
using Flags = MyString<FlagsTag>;
void foo( Hash ) {}
int main()
{
Hash hash( "12345" );
Flags flags( "--foo" );
foo( hash ); // that's fine
// you can already use them like strings in *some* contexts
std::cout << hash << " - " << flags << std::endl;
std::cout << ( hash == "12345" ) << std::endl;
// but they are not compatible types:
// won't compile:
// foo( flags );
// std::cout << ( hash == flags ) << std::endl;
}
The design you are aiming for is inheritance, as in the other answer here(*). But you should not inherit from std::string. You can find many discussions about it, for example: Inheriting and overriding functions of a std::string?.
It leaves you with your first idea, actually implementing the concept of composition.
(*) I would have commented in that answer instead of opening a new answer, but I can't comment yet.
This all sounds a bit bass ackwards. You want to have the same name for multiple functions that do different things to different objects. That's rather strange, because the typical approach is to have the same name for functions that do different things.
Not passing "the wrong things" is largely up to the programmer, you should remember what you are doing, and to what. And to test your code as you write it, and have tests that you run regularly to avoid regressions.
The other approach is to have a set of classes that hold your data, and have a common interface, such as this:
class OptionBase
{
public:
OptionBase(const std::string &s) : str(s) {}
virtual void Process() = 0;
virtual std::string Value() { return str; }
virtual ~OptionBase() {}
protected:
std::string str;
};
class FlagOption: public OptionBase
{
public:
FlagOption(const std::string& s) : OptionBase(s) {}
void Process() override { ... do stuff here ... }
};
class HashOption: public OptionBase
{
public:
HashOption(const std::string& s) : OptionBase(s) {}
void Process() override { ... do has stuff here ... }
};
class FunctionName: public OptoonBase
{
... you get the idea ...
};
Now you can "process" all your OptionBase type things in a consistent manner, calling the same processing function on each of them. But I'm not sure that's what you were looking for.
I'm trying to make a list of template classes of variable types. So the idea is to loop of a list of objects that all have a common function, e.g. getValue, but a different type. The type could be any type, raw types or objects.
I need this because i want to have a class that has a list of attributes of different types that i want to be able to construct at runtime.
So my class would look something like:
class MyClass {
std::list<Attribute<?>*> attributes;
};
And my attribute template:
template<typename T>
class Attribute {
public:
Test(const T &t) : _t(t) {}
T getValue() const { return _t; }
void setValue(const T &t) { _t = t; }
private:
T _t;
};
int main() {
MyClass myClass;
myClass.attributes.push_back(new Attribute<int>(42));
myClass.attributes.push_back(new Attribute<double>(42.0));
}
As you can see the list of MyClass i put ? because that is my problem. I dont know how to make a list that will take different types of my Attribute template, i.e. int, double etc.
std::list<Attribute<?> *> attributes;
In Java, generics can be used for that. Is it possible in C++ to do this with somekind of construction? I tried using variadic templates but that doesnt seem to help solving my problem.
I need this but not in Java, in C++:
public class GenericAttribute<T> {
private T value;
public GenericAttribute (T value) {
setValue(value);
}
public T getValue() {
return value;
}
public void setValue(T value) {
this.value = value;
}
}
public static void main(String[] args) {
class Custom {
public Custom() {}
#Override public String toString() {
return "My custom object";
}
}
List<GenericAttribute<?>> attributes = new ArrayList<GenericAttribute<?>>();
attributes.add(new GenericAttribute<Integer>(1));
attributes.add(new GenericAttribute<Double>(3.1415926535));
attributes.add(new GenericAttribute<Custom>(new Custom()));
for (GenericAttribute<?> attr : attributes) {
System.out.println(attr.getValue());
}
}
Output:
1
3.1415926535
My custom object
Thanks for the help!
Version 3: Very Advanced (do not try that at home :D)
class Attribute {
private:
struct Head {
virtual ~Head() {}
virtual void *copy() = 0;
const type_info& type;
Head(const type_info& type): type(type) {}
void *data() { return this + 1; }
};
template <class T> struct THead: public Head {
THead(): Head(typeid(T)) {}
virtual ~THead() override { ((T*)data())->~T(); }
virtual void *copy() override {
return new(new(malloc(sizeof(Head) + sizeof(T)))
THead() + 1) T(*(const T*)data()); }
};
void *data;
Head *head() const { return (Head*)data - 1; }
void *copy() const { return data ? head()->copy() : nullptr; }
public:
Attribute(): data(nullptr) {}
Attribute(const Attribute& src): data(src.copy()) {}
Attribute(Attribute&& src): data(src.data) { src.data = nullptr; }
template <class T> Attribute(const T& src): data(
new(new(malloc(sizeof(Head) + sizeof(T))) THead<T>() + 1) T(src)) {}
~Attribute() {
if(!data) return;
Head* head = this->head();
head->~Head(); free(head); }
bool empty() const {
return data == nullptr; }
const type_info& type() const {
assert(data);
return ((Head*)data - 1)->type; }
template <class T>
T& value() {
if (!data || type() != typeid(T))
throw bad_cast();
return *(T*)data; }
template <class T>
const T& value() const {
if (!data || type() != typeid(T))
throw bad_cast();
return *(T*)data; }
template <class T>
void setValue(const T& it) {
if(!data)
data = new(new(malloc(sizeof(Head) + sizeof(T)))
THead<T>() + 1) T(it);
else {
if (type() != typeid(T)) throw bad_cast();
*(T*)data = it; }}
public:
static void test_me() {
vector<Attribute> list;
list.push_back(Attribute(1));
list.push_back(3.14);
list.push_back(string("hello world"));
list[1].value<double>() = 3.141592;
list.push_back(Attribute());
list[3].setValue(1.23f);
for (auto& a : list) {
cout << "type = " << a.type().name()
<< " value = ";
if(a.type() == typeid(int)) cout << a.value<int>();
else if (a.type() == typeid(double)) cout << a.value<double>();
else if (a.type() == typeid(string)) cout << a.value<string>();
else if (a.type() == typeid(float)) cout << a.value<float>();
cout << endl;
}
}
};
Output:
type = i value = 1
type = d value = 3.14159
type = Ss value = hello world
type = f value = 1.23
Explanation:
Attribute contains data pointer, which is initializaed by this strange placement new: new(new(malloc(sizeof(Head) + sizeof(T))) THead<T>() + 1) T(src) which first allocates enough room for the Head (should be 2*sizeof(void*) which should be just fine for any allignment of any architecture) and the type itself, constructs THead<T>() (initializes pointer to virtual method table and type info) and moves the pointer after the head = at the place we want data. The object is then constructed by another placement new using copy-constructor (or move-constructor) T(src). struct Head has two virtual functions - destructor and copy() which is implemented in THead<T> and used in Attribute(const Attribute&) copy-constructor. Finally ~Attribute() destructor calls ~Head() virtual destructor and releases the memory (if data != nullptr).
Version 1: Simple Attribute List
#include <vector>
#include <typeinfo>
#include <iostream>
#include <cstdlib>
#include <new>
using namespace std;
class Attributes {
public:
typedef pair<const type_info&,void*> value_type;
typedef vector<value_type> vect;
typedef vect::const_iterator const_iterator;
template <class T>
void add(const T& value) {
data.push_back(pair<const type_info&,void*>(
typeid(T), new(malloc(sizeof(T))) T(value))); }
const_iterator begin() const {
return data.begin(); }
const_iterator end() const {
return data.end(); }
private:
vect data;
} attrs;
int main() {
attrs.add(1);
attrs.add(3.14);
for (auto a : attrs) {
cout << a.first.name() << " = ";
if(a.first == typeid(int))
cout << *(int*)a.second;
else if(a.first == typeid(double))
cout << *(double*)a.second;
cout << endl;
}
}
Output:
i = 1
d = 3.14
Version 2 (named attributes):
#include <string>
#include <unordered_map>
#include <typeinfo>
#include <iostream>
#include <cstdlib>
#include <new>
using namespace std;
class Attributes {
public:
typedef pair<const type_info&,void*> value_type;
typedef unordered_map<string,value_type> map;
typedef map::const_iterator const_iterator;
template <class T>
bool add(const string& name, const T& value) {
auto it = data.insert(make_pair(
name, value_type(typeid(T), nullptr)));
if (!it.second) return false;
it.first->second.second = new(malloc(sizeof(T))) T(value);
return true; }
template <class T>
const T& get(const string& name) const {
auto it = data.at(name);
if (it.first != typeid(T)) throw bad_cast();
return *(T*)it.second; }
const_iterator begin() const {
return data.begin(); }
const_iterator end() const {
return data.end(); }
void erase(const_iterator it) {
free(it->second.second);
data.erase(it); }
bool remove(const string& name) {
auto it = data.find(name);
if (it == data.end()) return false;
free(it->second.second);
data.erase(it);
return true; }
private:
map data;
} attrs;
int main() {
attrs.add("one", 1);
attrs.add("pi", 3.14);
cout << "pi = " << attrs.get<double>("pi") << endl;
attrs.remove("pi");
for (auto a : attrs) {
cout << a.first << " = ";
if(a.second.first == typeid(int))
cout << *(int*)a.second.second;
else if(a.second.first == typeid(double))
cout << *(double*)a.second.second;
cout << endl;
}
}
Take a look at variant - this is a class that can be one of a number of different types, but you don't mind which until you need to operate on the values, in which case you can use the visitor pattern to visit all the types.
It is effectively a C++ type-aware version of the C 'union' construct but as it 'knows' which type was set, it can offer type safety.
The biggest issue with variants is that if you expose your implementation and allow any client to put pretty much any type into your variant (attributes.push_back(new Attribute<Widget>(myWidget));), you're going to be unable to do anything with it. E.g. if you want to do 'sum' on all the values put into your attributes, you'd need them to be convertible to a numeric representation and a Widget might not be.
The bigger question is what are you trying to do with them once you've captured these items as Attributes? Enumerating through them calling getValue() is going to give you different results depending on what types you put in. A visitor object would work, but it's still not clear what value this would bring.
It could be that you need something different, such as an interface, e.g. IAttribute that abstracts the underlying type as long as it conforms to the interface which has a getValueAsDouble() method or getValueAsString() method, which you could do to any type that got passes in - no need for variant or visitor in this case.
As Attribute<int> is different type than Attribute<double>, you can't use list or vector without creating a common base type.
Alternatively, you may store different type into a std::tuple.
Following may help:
template <typename ... Ts>
class MyClass {
public:
MyClass(const Ts&... args) : attributes(args...) {}
private:
std::tuple<Attribute<Ts>...> attributes;
};
int main()
{
MyClass<int, double> myClass(42, 42.0);
return 0;
}
As you already pointed out, in java it is much easier to do so because all classes extends java.lang.Object. In C(++), there is a similar way, but only for pointers - you can use void* for this. Your list will look something like this then:
std::list<Attribute<void*> *> attributes;
Sure, a void* doesn't save the type. If you need, add this field to your Attribute-class:
public:
std::type_info type;
Then, if you create an instance of Attributre, do this (probably from the constructor):
type = typeinfo(type_to_store);
Of corse, if you do so from the constructor, you'll need to run typeinfo in the code that calls the constructor.
Then, you can get the name of the class back from that field and the instance back from your void*:
std::string name = attribute->type_info.name();
void * instance = attribute->getValue();
What operations do you want to perform on this collection? Do you want to, say, call getValue on all of the Attribute<int> instances and ignore the others? In that case, a base class is fine—you just don’t make the getValue member function virtual (because its type depends on the subclass) and use RTTI to recover the type information at runtime:
struct AnyAttribute {
// Needs at least one virtual function to support dynamic_cast.
virtual ~AnyAttribute() {}
};
template<typename T>
struct Attribute : AnyAttribute { … };
int main() {
std::vector<AnyAttribute*> attributes;
attributes.push_back(new Attribute<int>(13));
attributes.push_back(new Attribute<int>(42));
attributes.push_back(new Attribute<double>(2.5));
for (const auto attribute : attributes) {
if (const auto int_attribute = dynamic_cast<Attribute<int>>(attribute)) {
std::cout << int_attribute->getValue() << '\n';
}
}
}
An obvious, but naive solution will be:
inherit Attribute<T> from base AttributeBase
store AttributeBase (smart-)pointers in container (downcast)
when reading container element, somehow figure out its type (RTTI)
cast back to derived Attribute<T> (upcast)
You can beautify this ugly solution by adding another level of indirection: make a generic container, that stores generic containers for each attribute, so casting will happen under the hood.
You can use integrated to language RTTI features, such as type_info but as far as I know, it's reliability is questionable. Better solution will be to wrap up some kind of static unique id to each Attribute<T> class and put an accessor to AttributeBase to retrieve it. You can add a typedef to relevant Attribute<T> to your unique id class to make casting easier.
So far so good, but in modern C++, we know, that when you need RTTI, it, probably, means that there is something wrong with your overall code design.
I don't know what exact task you have, but my "gut feelings" say me that you will probably can eliminate need of RTTI by using multiple dispatch (double dispatch), such as Visitor pattern in your code (they always say that when see RTTI).
Also, check some other tricks for inspiration:
More C++ Idioms/Coercion by Member Template
Note: I know similar questions to this have been asked on SO before, but I did not find them helpful or very clear.
Second note: For the scope of this project/assignment, I'm trying to avoid third party libraries, such as Boost.
I am trying to see if there is a way I can have a single vector hold multiple types, in each of its indices. For example, say I have the following code sample:
vector<something magical to hold various types> vec;
int x = 3;
string hi = "Hello World";
MyStruct s = {3, "Hi", 4.01};
vec.push_back(x);
vec.push_back(hi);
vec.push_back(s);
I've heard vector<void*> could work, but then it gets tricky with memory allocation and then there is always the possibility that certain portions in nearby memory could be unintentionally overridden if a value inserted into a certain index is larger than expected.
In my actual application, I know what possible types may be inserted into a vector, but these types do not all derive from the same super class, and there is no guarantee that all of these types will be pushed onto the vector or in what order.
Is there a way that I can safely accomplish the objective I demonstrated in my code sample?
Thank you for your time.
The objects hold by the std::vector<T> need to be of a homogenous type. If you need to put objects of different type into one vector you need somehow erase their type and make them all look similar. You could use the moral equivalent of boost::any or boost::variant<...>. The idea of boost::any is to encapsulate a type hierarchy, storing a pointer to the base but pointing to a templatized derived. A very rough and incomplete outline looks something like this:
#include <algorithm>
#include <iostream>
class any
{
private:
struct base {
virtual ~base() {}
virtual base* clone() const = 0;
};
template <typename T>
struct data: base {
data(T const& value): value_(value) {}
base* clone() const { return new data<T>(*this); }
T value_;
};
base* ptr_;
public:
template <typename T> any(T const& value): ptr_(new data<T>(value)) {}
any(any const& other): ptr_(other.ptr_->clone()) {}
any& operator= (any const& other) {
any(other).swap(*this);
return *this;
}
~any() { delete this->ptr_; }
void swap(any& other) { std::swap(this->ptr_, other.ptr_); }
template <typename T>
T& get() {
return dynamic_cast<data<T>&>(*this->ptr_).value_;
}
};
int main()
{
any a0(17);
any a1(3.14);
try { a0.get<double>(); } catch (...) {}
a0 = a1;
std::cout << a0.get<double>() << "\n";
}
As suggested you can use various forms of unions, variants, etc. Depending on what you want to do with your stored objects, external polymorphism could do exactly what you want, if you can define all necessary operations in a base class interface.
Here's an example if all we want to do is print the objects to the console:
#include <iostream>
#include <string>
#include <vector>
#include <memory>
class any_type
{
public:
virtual ~any_type() {}
virtual void print() = 0;
};
template <class T>
class concrete_type : public any_type
{
public:
concrete_type(const T& value) : value_(value)
{}
virtual void print()
{
std::cout << value_ << '\n';
}
private:
T value_;
};
int main()
{
std::vector<std::unique_ptr<any_type>> v(2);
v[0].reset(new concrete_type<int>(99));
v[1].reset(new concrete_type<std::string>("Bottles of Beer"));
for(size_t x = 0; x < 2; ++x)
{
v[x]->print();
}
return 0;
}
In order to do that, you'll definitely need a wrapper class to somehow conceal the type information of your objects from the vector.
It's probably also good to have this class throw an exception when you try to get Type-A back when you have previously stored a Type-B into it.
Here is part of the Holder class from one of my projects. You can probably start from here.
Note: due to the use of unrestricted unions, this only works in C++11. More information about this can be found here: What are Unrestricted Unions proposed in C++11?
class Holder {
public:
enum Type {
BOOL,
INT,
STRING,
// Other types you want to store into vector.
};
template<typename T>
Holder (Type type, T val);
~Holder () {
// You want to properly destroy
// union members below that have non-trivial constructors
}
operator bool () const {
if (type_ != BOOL) {
throw SomeException();
}
return impl_.bool_;
}
// Do the same for other operators
// Or maybe use templates?
private:
union Impl {
bool bool_;
int int_;
string string_;
Impl() { new(&string_) string; }
} impl_;
Type type_;
// Other stuff.
};
I've got an interesting problem that's cropped up in a sort of pass based compiler of mine. Each pass knows nothing of other passes, and a common object is passed down the chain as it goes, following the chain of command pattern.
The object that is being passed along is a reference to a file.
Now, during one of the stages, one might wish to associate a large chunk of data, such as that file's SHA512 hash, which requires a reasonable amount of time to compute. However, since that chunk of data is only used in that specific case, I don't want all file references to need to reserve space for that SHA512. However, I also don't want other passes to have to recalculate the SHA512 hash over and over again. For example, someone might only accept files which match a given list of SHA512s, but they don't want that value printed when the file reference gets to the end of the chain, or perhaps they want both, or... .etc.
What I need is some sort of container which contain only one of a given type. If the container does not contain that type, it needs to create an instance of that type and store it somehow. It's basically a dictionary with the type being the thing used to look things up.
Here's what I've gotten so far, the relevant bit being the FileData::Get<t> method:
class FileData;
// Cache entry interface
struct FileDataCacheEntry
{
virtual void Initalize(FileData&)
{
}
virtual ~FileDataCacheEntry()
{
}
};
// Cache itself
class FileData
{
struct Entry
{
std::size_t identifier;
FileDataCacheEntry * data;
Entry(FileDataCacheEntry *dataToStore, std::size_t id)
: data(dataToStore), identifier(id)
{
}
std::size_t GetIdentifier() const
{
return identifier;
}
void DeleteData()
{
delete data;
}
};
WindowsApi::ReferenceCounter refCount;
std::wstring fileName_;
std::vector<Entry> cache;
public:
FileData(const std::wstring& fileName) : fileName_(fileName)
{
}
~FileData()
{
if (refCount.IsLastObject())
for_each(cache.begin(), cache.end(), std::mem_fun_ref(&Entry::DeleteData));
}
const std::wstring& GetFileName() const
{
return fileName_;
}
//RELEVANT METHOD HERE
template<typename T>
T& Get()
{
std::vector<Entry>::iterator foundItem =
std::find_if(cache.begin(), cache.end(), boost::bind(
std::equal_to<std::size_t>(), boost::bind(&Entry::GetIdentifier, _1), T::TypeId));
if (foundItem == cache.end())
{
std::auto_ptr<T> newCacheEntry(new T);
Entry toInsert(newCacheEntry.get(), T::TypeId);
cache.push_back(toInsert);
newCacheEntry.release();
T& result = *static_cast<T*>(cache.back().data);
result.Initalize(*this);
return result;
}
else
{
return *static_cast<T*>(foundItem->data);
}
}
};
// Example item you'd put in cache
class FileBasicData : public FileDataCacheEntry
{
DWORD dwFileAttributes;
FILETIME ftCreationTime;
FILETIME ftLastAccessTime;
FILETIME ftLastWriteTime;
unsigned __int64 size;
public:
enum
{
TypeId = 42
}
virtual void Initialize(FileData& input)
{
// Get file attributes and friends...
}
DWORD GetAttributes() const;
bool IsArchive() const;
bool IsCompressed() const;
bool IsDevice() const;
// More methods here
};
int main()
{
// Example use
FileData fd;
FileBasicData& data = fd.Get<FileBasicData>();
// etc
}
For some reason though, this design feels wrong to me, namely because it's doing a whole bunch of things with untyped pointers. Am I severely off base here? Are there preexisting libraries (boost or otherwise) which would make this clearer/easier to understand?
As ergosys said already, std::map is the obvious solution to your problem. But I can see you concerns with RTTI (and the associated bloat). As a matter of fact, an "any" value container does not need RTTI to work. It is sufficient to provide a mapping between a type and an unique identifier. Here is a simple class that provides this mapping:
#include <stdexcept>
#include <boost/shared_ptr.hpp>
class typeinfo
{
private:
typeinfo(const typeinfo&);
void operator = (const typeinfo&);
protected:
typeinfo(){}
public:
bool operator != (const typeinfo &o) const { return this != &o; }
bool operator == (const typeinfo &o) const { return this == &o; }
template<class T>
static const typeinfo & get()
{
static struct _ti : public typeinfo {} _inst;
return _inst;
}
};
typeinfo::get<T>() returns a reference to a simple, stateless singleton which allows comparisions.
This singleton is created only for types T where typeinfo::get< T >() is issued anywhere in the program.
Now we are using this to implement a top type we call value. value is a holder for a value_box which actually contains the data:
class value_box
{
public:
// returns the typeinfo of the most derived object
virtual const typeinfo& type() const =0;
virtual ~value_box(){}
};
template<class T>
class value_box_impl : public value_box
{
private:
friend class value;
T m_val;
value_box_impl(const T &t) : m_val(t) {}
virtual const typeinfo& type() const
{
return typeinfo::get< T >();
}
};
// specialization for void.
template<>
class value_box_impl<void> : public value_box
{
private:
friend class value_box;
virtual const typeinfo& type() const
{
return typeinfo::get< void >();
}
// This is an optimization to avoid heap pressure for the
// allocation of stateless value_box_impl<void> instances:
void* operator new(size_t)
{
static value_box_impl<void> inst;
return &inst;
}
void operator delete(void* d)
{
}
};
Here's the bad_value_cast exception:
class bad_value_cast : public std::runtime_error
{
public:
bad_value_cast(const char *w="") : std::runtime_error(w) {}
};
And here's value:
class value
{
private:
boost::shared_ptr<value_box> m_value_box;
public:
// a default value contains 'void'
value() : m_value_box( new value_box_impl<void>() ) {}
// embedd an object of type T.
template<class T>
value(const T &t) : m_value_box( new value_box_impl<T>(t) ) {}
// get the typeinfo of the embedded object
const typeinfo & type() const { return m_value_box->type(); }
// convenience type to simplify overloading on return values
template<class T> struct arg{};
template<class T>
T convert(arg<T>) const
{
if (type() != typeinfo::get<T>())
throw bad_value_cast();
// this is safe now
value_box_impl<T> *impl=
static_cast<value_box_impl<T>*>(m_value_box.get());
return impl->m_val;
}
void convert(arg<void>) const
{
if (type() != typeinfo::get<void>())
throw bad_value_cast();
}
};
The convenient casting syntax:
template<class T>
T value_cast(const value &v)
{
return v.convert(value::arg<T>());
}
And that's it. Here is how it looks like:
#include <string>
#include <map>
#include <iostream>
int main()
{
std::map<std::string,value> v;
v["zero"]=0;
v["pi"]=3.14159;
v["password"]=std::string("swordfish");
std::cout << value_cast<int>(v["zero"]) << std::endl;
std::cout << value_cast<double>(v["pi"]) << std::endl;
std::cout << value_cast<std::string>(v["password"]) << std::endl;
}
The nice thing about having you own implementation of any is, that you can very easily tailor it to the features you actually need, which is quite tedious with boost::any. For example, there are few requirements on the types that value can store: they need to be copy-constructible and have a public destructor. What if all types you use have an operator<<(ostream&,T) and you want a way to print your dictionaries? Just add a to_stream method to box and overload operator<< for value and you can write:
std::cout << v["zero"] << std::endl;
std::cout << v["pi"] << std::endl;
std::cout << v["password"] << std::endl;
Here's a pastebin with the above, should compile out of the box with g++/boost: http://pastebin.com/v0nJwVLW
EDIT: Added an optimization to avoid the allocation of box_impl< void > from the heap:
http://pastebin.com/pqA5JXhA
You can create a hash or map of string to boost::any. The string key can be extracted from any::type().