繁体   English   中英

这是 C++ 中的合法语法吗? 以及如何使用 crtp 技巧?

[英]Is this legal syntax in c++? and How do I use crtp trick?

template<template<typename>class Derived>
class Base{
    public:
        void interface(){
             static_cast<Derived&>(*this).something();
        }
};

template<typename T>
class Derived:public Base<Derived> {
    ...
};

Derived 需要一个模板参数,但我只对 Base 中的 Derived 类使用未命名参数。 我可以使用这种语法吗? 我修什么? 如何在 Base 中访问 Derived?


我可以在 base 中使用 dType = typename Derived::type 添加吗? 在 gcc 10.2 版中,我遇到了这样的错误;

test.cpp: In instantiation of 'class Base<Derived<int> >':
test.cpp:22:7:   required from 'class Derived<int>'
test.cpp:30:24:   required from here
test.cpp:13:9: error: invalid use of incomplete type 'class Derived<int>'
   13 |   using dType = typename derived::Type;
      |         ^~~~~
test.cpp:22:7: note: declaration of 'class Derived<int>'
   22 | class Derived:public Base<Derived<T>>{

我只是在您的代码中添加 using dType = Derived::Type 。

您可以在Derived明确地为模板参数指定一个名称:

template<typename Derived>
class Base{
    public:
        void interface(){
             typename Derived::type some_variable;
             static_cast<Derived&>(*this).something();
        }
};

template<typename T>
class Derived:public Base<Derived<T>> {
public
    using type = T;
    ...
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM