为什么我上课不是模板错误?

时间:2019-04-06 13:49:34

标签: c++ g++

我收到的“ 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/

1 个答案:

答案 0 :(得分:2)

没有诸如“没有模板参数的模板类”之类的东西。语法template <>引入了现有模板的显式特化。

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

template <typename> class Storage8;

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

或者,如果您对某些代码会尝试定义已声明的模板有些偏执,则可以定义一个始终无效的定义(尽管这并不能真正阻止代码添加更多显式或部分专业化的内容):< / p>

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

(请注意,您不能只static_assert(false, ...):如果条件不“依赖”模板参数,即使模板从未实例化,也会触发错误。)