Using a templated parameter's value_type

后端 未结 3 1589
-上瘾入骨i
-上瘾入骨i 2021-02-13 01:54

How is one supposed to use a std container\'s value_type?
I tried to use it like so:

#include 

using namespace std;

template 

        
相关标签:
3条回答
  • 2021-02-13 01:54

    Here is a full implementation of the accepted answers above, in case it helps anyone.

    #include <iostream>
    #include <list>
    
    template <typename T>
    class C1 {
      private:
        T container;
        typedef typename T::value_type CT;
      public:
        void push(CT& item) {
            container.push_back(item);
        }
    
        CT pop (void) {
            CT item = container.front();
            container.pop_front();
            return item;
        }
    };
    
    int main() {
        int i = 1;
        C1<std::list<int> > c;
        c.push(i);
        std::cout << c.pop() << std::endl;
    }
    
    0 讨论(0)
  • 2021-02-13 01:59

    You have to use typename:

    typename T::value_type pop()
    

    and so on.

    The reason is that the compiler cannot know whether T::value_type is a type of a member variable (nobody hinders you from defining a type struct X { int value_type; }; and pass that to the template). However without that function, the code could not be parsed (because the meaning of constructs changes depending on whether some identifier designates a type or a variable, e.g.T * p may be a multiplication or a pointer declaration). Therefore the rule is that everything which might be either type or variable and is not explicitly marked as type by prefixing it with typename is considered a variable.

    0 讨论(0)
  • 2021-02-13 02:07

    Use the typename keyword to indicate that it's really a type.

    void push(typename T::value_type& item)
    
    typename T::value_type pop()
    
    0 讨论(0)
提交回复
热议问题