Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
819 views
in Technique[技术] by (71.8m points)

c++ - When should I use the keyword "typename" when using templates

I've been working lately on a small project, and I couldn't figure out something..

I've been given a .h file that was containing a class, using a typename template. Inside that class there was a private class.

template <typename T>
class Something
{
public:
        Something();
        ~Something();

        Node* Function1(int index);
        int Index(const T& id);


private:
        class Node()
        {
                public:
                T id;

                //Imagine the rest for the Node


        };      
};

The problem occured when I wanted to define the functions of the class "Something"

Here's how I was doing it (in a .inl file)

template<typename T>
Node* Something::Function1(int index) //Is the return type well written?
{
        // returns the node at the specified index
}

template<typename T>
int Something::Index(const T& id) //Is the parameter type well specified?
{
        // returns the index of the node with the specified id
}

So the bugging part was in the definitions part... Do I have to tell the compiler that the return type (in this case Node*) uses the typename template (like this: typename Node*) ? And what about the parameter ? typename const Node& ?

So basically, when do I have to specify wether the function/parameter uses a template?

Thanks for your time.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For Function1, you need to tell the compiler what Node is -- in this case, it's a nested type inside Something<T>. Because it's dependent on T (it's a dependent name), you need to tell the compiler it's a type, so you must write it as typename Something<T>::Node. The issue is that there might be some T for which Something<T>::Node isn't actually a type (i.e. if you partially specialize Something<T>).

For Index, what you have is fine -- const T& is just a reference to a const T, and the compiler knows what T is.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...