Home Using default Traits apart from the specializations

# Using default Traits apart from the specializations

user6962
1#
user6962 Published in September 21, 2018, 8:03 am

What I want to do is to create a generic traits class with the default logic and then write code to specialize each specific case with only the things that are different from the generic case. My goal is to remove code duplication and avoid writing unnecessary code.

I'll give you an example:

int genericFunction(); // defined somewhere else
int specialFunction(); // defined somewhere else

template<int id>
struct IdTraits
{
using MyType = int;
using AnotherType = double;
static constexpr auto&& f = genericFunction;
};

template<>
struct IdTraits<1>
{
// Using MyType and AnotherType of IdTraits generic case [how?]
static constexpr auto&& f = specialFunction;
};

template<>
struct IdTraits<2>
{
// Using MyType and f of IdTraits generic case [how?]
using AnotherType = char;
};

template<int id, class Traits = IdTraits<id>>
struct General
{
void foo(int arg)
{
Traits::MyType myType;
Traits::AnotherType anotherType;
Traits::f(arg);
// Do stuff with myType and anotherType
}

};


Do you think is theoretically possible to do something like this?

• You can have another Trait checking if the element is present inside IdTrait<id>, and setting the default type/function if not. – O'Neil Feb 12 at 11:46
• interesting, could you elaborate? – svoltron Feb 12 at 11:49