Sweeney Todd
Sweeney Todd

Reputation: 880

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)

Upvotes: 4

Views: 2853

Answers (1)

Alan Birtles
Alan Birtles

Reputation: 36614

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;
};

Upvotes: 11

Related Questions