提问者:小点点

当给定一个类型时,我可以将结构设置为“使用”一个类型吗?('非模板结构的显式专用化')


我有下面的结构,将有许多不同的“输入”和“输出”类型的结构。

#include <string>

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

这会导致错误:

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

这应该可以用作orselding::orseldingt,在本例中,T可以是const char*,但可以是其他类型,因为添加了更多类型,例如。

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

然后

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

让我相信这是可行的来源:https://en.cppreference.com/W/cpp/utility/hash,https://en.cppreference.com/W/cpp/types/remove_reference。

有其他的问题与这个相同的错误,但他们似乎在尝试不同的东西,使他们在这里不相关。

我使用的是GNU++2A。


共1个答案

匿名用户

您只是忘记了声明主模板。

#include <string>

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

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

如果没有它,正如错误所说的,对应的就不是类模板(或者任何东西),因此不能为它定义专门化。

与其查找无关内容的引用,例如std::hashstd::remove_reference,不如复习一下C++书籍中关于模板专门化的章节。