相关疑难解决方法(0)

无效使用不完整类型

我正在尝试在项目中使用子类的typedef,我在下面的示例中已经分离了我的问题.

有谁知道我哪里出错了?

template<typename Subclass>
class A {
    public:
        //Why doesn't it like this?
        void action(typename Subclass::mytype var) {
            (static_cast<Subclass*>(this))->do_action(var);
        }
};

class B : public A<B> {
    public:
        typedef int mytype;

        B() {}

        void do_action(mytype var) {
            // Do stuff
        }
};

int main(int argc, char** argv) {
    B myInstance;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这是我得到的输出:

sean@SEAN-PC:~/Documents/LucadeStudios/experiments$ g++ -o test test.cpp
test.cpp: In instantiation of ‘A<B>’:
test.cpp:10:   instantiated from here
test.cpp:5: error: invalid use of incomplete type ‘class B’
test.cpp:10: error: forward …
Run Code Online (Sandbox Code Playgroud)

c++ templates typedef crtp

53
推荐指数
2
解决办法
10万
查看次数

iterator_trait的典型用例是什么?

我是C++的新手,所以请耐心等待.我想了解STL iterator_traits.在"C++标准库"一书中,iterator_traits结构定义如下:

template <class T>
struct iterator_traits{
  typedef typename T::value_type value_type
  typedef typename T::difference_type difference_type
  typedef typename T::iterator_category iterator_category
  typedef typename T::pointer pointer
  typedef typename T::reference reference
}
Run Code Online (Sandbox Code Playgroud)

所以在我看来,它正在重新暴露T已经暴露的子类型.继续前进,本书给出了如何使用它的示例,如下所示

template <class MyIterator>
void do_something(MyIterator start, MyIterator end) {
    typedef typename iterator_traits<MyIterator>::value_type value_type
    value_type v = *start
    .....
Run Code Online (Sandbox Code Playgroud)

我的问题是为什么我在这里需要这个iterator_traits结构,如果想要获得它value_type,我不能MyIterator直接获得它吗?我的困惑似乎来自于我(肯定是不正确的)理解,即子类型的信息必须来源于template <class T>用于实例化iterator_trait.所以如果你能解释一下,最好用一个例子说明为什么以及在哪里我需要iterator_traits,这将是非常有帮助的.

c++ iterator stl traits iterator-traits

21
推荐指数
1
解决办法
4351
查看次数

标签 统计

c++ ×2

crtp ×1

iterator ×1

iterator-traits ×1

stl ×1

templates ×1

traits ×1

typedef ×1