简体   繁体   English

您如何使用模板来专门化常量

[英]How do you specialize constants using templates

I want to return a different constant for each different type that is used for the templated class. 我想为用于模板化类的每个不同类型返回不同的常量。

For example, when the class is 例如,当班级是

Stack< int > I want the constant EMPTY = -99 Stack <int>我想要常量EMPTY = -99

when the class is Stack< char > I want the constant EMPTY to be '\\0'. 当类为Stack <char>时,我希望常量EMPTY为'\\ 0'。

So far I have been searching for the syntax for how to explicitly specialize variables and have no idea where to start looking for this. 到目前为止,我一直在寻找语法,以了解如何显式地专门化变量,却不知道从哪里开始寻找。

A simple code example would be amazing, as this issue has been bugging me for a while. 一个简单的代码示例将是惊人的,因为这个问题困扰了我一段时间。

What I have so far (without constants) is: 到目前为止,我所拥有的(没有常量)是:

template<class T>
class Stack {
private:
       T* items_;
        //EMPTY constant here

public:

    Stack();

    ~Stack();

    void push(T value);

    T pop();
};
template<class T>
class Stack {
private:
       T* items_;
       static T EMPTY;

public:
    Stack();
    ~Stack();

    void push(T value);
    T pop();
};

extern template<> int Stack<int>::EMPTY;
extern template<> char Stack<char>::EMPTY;

Then in a cpp file: 然后在一个cpp文件中:

template<> int Stack<int>::EMPTY = -99;
template<> char Stack<char>::EMPTY = '\0';

Note depending on usage this will limit the types you can instantiate your template with. 请注意,根据使用情况,这将限制可用于实例化模板的类型。

You might want to consider whether you want this to be part of your stack, or rather factor it out to a general traits class. 您可能要考虑是否要使其成为堆栈的一部分,或者将其分解为常规特征类。 Depending on what you do, it might be useful for other data structures. 根据您的操作,它可能对其他数据结构很有用。

template<typename T>
struct traits
{
    static T empty;
};
template<> int traits<int>::empty = 99;
template<> char traits<char>::empty = 0;


template<class T>
class Stack 
{
public:
    Stack()
    {
        T t = traits<T>::empty; 
    }
};

int main()
{
    Stack<int>(); 
    Stack<char>(); 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM