An idea on how to "simulate" a class attribute using template specialization:
#include <string>
#include <iostream>
// attribute classes: the default implementation returns some
// default values for the attributes properties
template<typename TheClass>
struct Attribute1{
static const int Value = 0;
};
template<typename TheClass>
struct Attribute2{
static const std::string Value(){
return "";
}
};
The default implementation of the attributes will be picked up by the compiler for a class without attributes:
// define a type without attributes
struct ClassWithoutAttributes{
};
If we want to apply the attributes to a class, we use template specialization:
// define a type with attributes; we "simulate" the attributes
// template specialization
struct ClassWithAttributes{
};
// template-specialize Attribute1 for the class we want to apply the
// attribute to...
template<>
struct Attribute1<ClassWithAttributes>{
static const int Value = 1;
};
// template-specialize Attribute2
template<>
struct Attribute2<ClassWithAttributes>{
static const std::string Value(){
return "SomeString";
}
};
We must apply (template-specialize) the attributes for every class we want them to be applied to:
class Item{
};
template<>
struct Attribute1<Item>{
static const int Value = 2;
};
Example:
// how to use the fake attributes:
void main(){
// no template specialization for "ClassWithoutAttributes" => the compiler picks up the "default" values
std::cout << "Attribute1 for type 'ClassWithoutAttributes' : " << Attribute1<ClassWithoutAttributes>::Value << std::endl;
std::cout << "Attribute2 for type 'ClassWithoutAttributes' : " << Attribute2<ClassWithoutAttributes>::Value() << std::endl;
// here the compiler picks up the attribute classes specialized for "ClassWithAttributes"
std::cout << "Attribute1 for type 'ClassWithAttributes' : " << Attribute1<ClassWithAttributes>::Value << std::endl;
std::cout << "Attribute2 for type 'ClassWithAttributes' : " << Attribute2<ClassWithAttributes>::Value() << std::endl;
}
In this way the attributes are "applied" to the class, and not to the instance as with multiple inheritance; the fundamental difference, anyway, is that in this case the attributes are evaluated at compile time, and not at run time.
EDIT: modified the example to show how to apply several attributes to a class and how to apply the same attribute to several classes.
Answering this question has been fun for me; at this point, anyway, I feel that the best advice on the subject is that you should not try to program in c++ as if it was c#. In any case, happy coding!