相关疑难解决方法(0)

C++静态多态(CRTP)并使用派生类中的typedef

我阅读了维基百科关于C++中用于执行静态(读取:编译时)多态的奇怪重复模板模式的文章.我想概括它,以便我可以根据派生类型更改函数的返回类型.(这似乎应该是可能的,因为基类型知道模板参数中的派生类型).不幸的是,以下代码将无法使用MSVC 2010进行编译(我现在没有轻松访问gcc所以我还没有尝试过).谁知道为什么?

template <typename derived_t>
class base {
public:
    typedef typename derived_t::value_type value_type;
    value_type foo() {
        return static_cast<derived_t*>(this)->foo();
    }
};

template <typename T>
class derived : public base<derived<T> > {
public:
    typedef T value_type;
    value_type foo() {
        return T(); //return some T object (assumes T is default constructable)
    }
};

int main() {
    derived<int> a;
}
Run Code Online (Sandbox Code Playgroud)

顺便说一下,我有一个使用额外模板参数的解决方法,但我不喜欢它 - 当在继承链上传递许多类型时会变得非常冗长.

template <typename derived_t, typename value_type>
class base { ... };

template <typename T>
class derived : public …
Run Code Online (Sandbox Code Playgroud)

c++ inheritance templates typedef crtp

62
推荐指数
3
解决办法
1万
查看次数

无效使用不完整类型

我正在尝试在项目中使用子类的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万
查看次数

标签 统计

c++ ×2

crtp ×2

templates ×2

typedef ×2

inheritance ×1