Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative to declaring a type alias inside a class

I am using a class (sf::Texture) from another library. I want to get the functionality of declaring a type alias inside that class, like:

class Texture
{
public:
    using ResourceId = TextureId;
    //...
}

so that I can do this in my code:

enum class TextureId
{
    texture1,
    texture2 //..etc
}

template<class ResourceType>
class ResourceContainer
{
public:
    ResourceContainer();
private:
    ResourceType* resource_;
    typename ResourceType::ResourceId id; // <--- this will have TextureId type
                                          // when we create this object 
                                          // with <sf::Texture>
}

However, as I mentioned, the Texture class is from another library so I can't edit its declaration.

I tried to declare it in my code as using sf::Texture::ResourceId = TextureId; but it doesn't work(Cannot resolve the symbol ResourceId).

So, is there an alternative to get the same functionality without adding ResourceId as the second template parameter?

(using C++17)

like image 573
Sweeney Todd Avatar asked Dec 18 '22 17:12

Sweeney Todd


1 Answers

You can just use a trait class to derive the ResourceId and specialise it for Texture. e.g:

template < typename T >
struct ResourceTypeTrait
{
  using ResourceId = typename T::ResourceId;
};

template <>
struct ResourceTypeTrait< Texture >
{
  using ResourceId = TextureId;
};

Then you can do:

template<class ResourceType>
class ResourceContainer
{
public:
    ResourceContainer();
private:
    ResourceType* resource_;
    typename ResourceTypeTrait< ResourceType >::ResourceId id;
};
like image 78
Alan Birtles Avatar answered Jan 08 '23 02:01

Alan Birtles