【问题标题】:Can I set up structs to 'using' a type when given a type? ('explicit specialization of non-template struct')给定类型时,我可以设置结构以“使用”类型吗? ('非模板结构的显式特化')
【发布时间】:2020-12-06 15:10:08
【问题描述】:

我有以下结构,其中有许多具有不同的“输入”和“输出”类型。

#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...

这应该可以用作Corresponding&lt;T&gt;::CorrespondingT,在这种情况下,T 可以是const char*,但也可以是其他类型,例如添加更多类型,例如

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

然后

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

让我相信这会奏效的来源:https://en.cppreference.com/w/cpp/utility/hashhttps://en.cppreference.com/w/cpp/types/remove_reference

还有其他问题与此相同的错误,但他们似乎在尝试不同的事情,使它们在这里不相关。

我正在使用 gnu++2a。

【问题讨论】:

    标签: c++ templates struct template-specialization


    【解决方案1】:

    您只是忘记声明主模板。

    #include <string>
    
    // You need this
    template <typename T>
    struct Corresponding;
    
    template <>
    struct Corresponding<const char*> {
        using CorrespondingT = std::string;
    };
    

    没有它,正如错误所说,Corresponding 不是类模板(或者实际上是任何东西),所以不能为它定义专业化。

    不要查找有关 std::hashstd::remove_reference 等不相关事物的参考资料,而是查看 C++ 书中有关模板专业化的章节。

    【讨论】:

    • 很遗憾,我没有这本书,但问题是我不知道它被称为“模板专业化”,这使得查找文档变得更加困难。
    • @Doot 你应该得到一个。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多