Doot
Doot

Reputation: 745

Can I set up structs to 'using' a type when given a type? ('explicit specialization of non-template struct')

I have the following struct and there will be many of these with different 'input' and 'output' types.

#include <string>

template <>
struct Corresponding<const char*> {
    using CorrespondingT = std::string;
};

This causes the error:

explicit specialization of non-template struct
      'Corresponding'
        template <> struct Corresponding<const char*> { using Correspond...

This should be usable as Corresponding<T>::CorrespondingT where T, in this case, could be const char*, but could be other types as more are added, e.g.

template <>
struct Corresponding<int> {
    using CorrespondingT = boost::multiprecision::cpp_int;
};

then

template <typename T> using GetCorresponding = typename Corresponding<T>::CorrespondingT;

Sources that led me to believe that this would work: https://en.cppreference.com/w/cpp/utility/hash, https://en.cppreference.com/w/cpp/types/remove_reference.

There have been other questions with this same error, but they seem to be attempting different things, making them not relevant here.

I'm using gnu++2a.

Upvotes: 0

Views: 146

Answers (1)

Asteroids With Wings
Asteroids With Wings

Reputation: 17454

You simply forgot to declare the primary template.

#include <string>

// You need this
template <typename T>
struct Corresponding;

template <>
struct Corresponding<const char*> {
    using CorrespondingT = std::string;
};

Without it, as the error says, Corresponding is not a class template (or indeed anything), so cannot have specialisations defined for it.

Instead of looking up references on unrelated things such as std::hash and std::remove_reference, review the chapter in your C++ book about template specialisations.

Upvotes: 3

Related Questions