首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >这是c++中的合法语法吗?我如何使用crtp技巧呢?

这是c++中的合法语法吗?我如何使用crtp技巧呢?
EN

Stack Overflow用户
提问于 2021-06-22 19:19:40
回答 1查看 84关注 0票数 1
代码语言:javascript
运行
复制
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中派生的类使用未命名的参数。我可以使用这个语法吗?我修了什么?如何访问在Base中派生的?

我可以在基础中使用dType = typename Derived::type进行添加吗?在gcc 10.2版本中,我得到了这样的错误;

代码语言:javascript
运行
复制
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>>{

我只是在代码中使用dType = Derived::Type进行添加。

EN

回答 1

Stack Overflow用户

发布于 2021-06-22 19:25:02

您可以在Derived中显式地为模板参数指定一个名称

代码语言:javascript
运行
复制
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;
    ...
};
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68082603

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档