为什么我上课不是模板错误? [关闭]

问题描述 投票:-4回答:1

我得到“Storage8”不是g ++中的模板错误,我不知道如何解决这个问题。

template <> // the following is a template class with no templated parameters
class Storage8<bool> // we're specializing Storage8 for bool
{
// What follows is just standard class implementation details
private:
    unsigned char m_data;

public:
    Storage8() : m_data(0)
    {
    }

    void set(int index, bool value)
    {
        // Figure out which bit we're setting/unsetting
        // This will put a 1 in the bit we're interested in turning on/off
        unsigned char mask = 1 << index;

        if (value)  // If we're setting a bit
            m_data |= mask;  // Use bitwise-or to turn that bit on
        else  // if we're turning a bit off
            m_data &= ~mask;  // bitwise-and the inverse mask to turn that bit off
    }

    bool get(int index)
    {
        // Figure out which bit we're getting
        unsigned char mask = 1 << index;
        // bitwise-and to get the value of the bit we're interested in
        // Then implicit cast to boolean
        return (m_data & mask);
    }
};

我还没有尝试过任何其他编译器。我认为它是编译器相关的问题或c ++标准问题。编辑::我正在关注课程模板专业化https://www.learncpp.com/cpp-tutorial/136-class-template-specialization/的本教程

c++ g++
1个回答
2
投票

没有“没有模板参数的模板类”这样的东西。语法qazxsw poi引入了现有模板的显式特化。

但您可以简单地声明主模板,而不是定义它。尝试将其与“错误”模板参数一起使用的任何代码都将导致编译器错误。

template <>

或者,如果您有点偏执,某些代码将尝试定义声明的模板,您可以创建一个始终无效的定义(尽管这并不能阻止代码添加更多显式或部分特化):

template <typename> class Storage8;

template <>
class Storage8<bool> {
// ...

(注意,你不能只做#include <type_traits> template <typename T> class Storage8 { static_assert(!std::is_same<T,T>::value, "Invalid type argument for Storage8<T>"); }; template <> class Storage8<bool> { // ... :如果条件不依赖于模板参数,即使模板从未实例化,错误也会触发。)

© www.soinside.com 2019 - 2024. All rights reserved.