相关疑难解决方法(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万
查看次数

CRTP - 访问不完整类型的成员

相关问题:,

在尝试了解CRTP几天后,似乎现在我比以前更了解:)

请考虑以下代码:

01 #include <iostream>
02 
03 template <class IMPL>
04 class Interace
05 {
06 public:
07     typedef typename IMPL::TYPE TYPE;  // ERROR: "...invalid use of incomplete type..."
08     void foo() { IMPL::impl(); }       // then why does this work?
09 };
10 
11 class Implementation : public Interface<Implementation>
12 {
13 public:
14    typedef int TYPE;
15    static void impl() { std::cout << "impl() " << std::endl; }
16 };
17 
18 
19 int …
Run Code Online (Sandbox Code Playgroud)

c++ crtp incomplete-type c++11

5
推荐指数
1
解决办法
990
查看次数

标签 统计

c++ ×2

crtp ×2

c++11 ×1

incomplete-type ×1

inheritance ×1

templates ×1

typedef ×1