c++ - 使用具有部分类特化的 CRTP?

标签 c++ c++11 templates template-meta-programming

我正在尝试将 operator [] 与类混合。我的问题是我已经部分特化了这个类,编译器不喜欢我没有为派生类指定模板参数:

#include <iostream>
#include <type_traits>

using namespace std;

template <typename T>
struct mixin {
    template <typename U>
    void operator[](U u) {
        cout << u;
    }
};


template <typename T, typename = void>
struct derived : mixin<derived> {};


template <typename T>
struct derived<T, 
    typename enable_if<
        is_same<T, int>{}
    >::type> : mixin<derived> {};


int main() {
    derived<int> d;
    d[3.14];
}

用 clang 给出:

test.cc:16:24: error: use of class template 'derived' requires template arguments
struct derived : mixin<derived> {};
                       ^~~~~~~
test.cc:16:8: note: template is declared here
struct derived : mixin<derived> {};
       ^
test.cc:23:22: error: use of class template 'derived' requires template arguments
    >::type> : mixin<derived> {};
                     ^~~~~~~
test.cc:16:8: note: template is declared here
struct derived : mixin<derived> {};
       ^

gcc 的帮助甚至更少:

test.cc:16:31: error: type/value mismatch at argument 1 in template parameter list for ‘template<class T> struct mixin’
 struct derived : mixin<derived> {};
                               ^
test.cc:16:31: note:   expected a type, got ‘derived’
test.cc:23:29: error: type/value mismatch at argument 1 in template parameter list for ‘template<class T> struct mixin’
     >::type> : mixin<derived> {};
                             ^
test.cc:23:29: note:   expected a type, got ‘derived’
test.cc: In function ‘int main()’:

我唯一的选择是在 mixin 子句中重新指定模板参数吗?

最佳答案

好吧,试试这个:

#include <iostream>
#include <type_traits>

using namespace std;

template <typename T>
struct mixin {
    template <typename U>
    void operator[](U u) {
        cout << u;
    }
};


template <typename T, typename = void>
struct derived : mixin<derived<T>> {};


template <typename T>
struct derived<T,
    typename enable_if<
        is_same<T, int>::value
    >::type> : mixin<derived<T>> {};


int main() {
    derived<int> d;
    d[3.14];
}

确实如此 work ...

我改变了什么:

  1. 使用 is_same<foo,bar>::value , 不是 is_same<foo,bar>{} 编辑: 嗯,看来您毕竟不需要更改它。整洁!
  2. 在使用mixin<derived> 时,不试图让编译器推导出派生的模板参数。 .你在那里方式太乐观了...

关于c++ - 使用具有部分类特化的 CRTP?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50670878/

相关文章:

c++ - 使用 -pthread 如何不违反 ODR 规则?

c++ - 尝试递增 initializer_list.begin() 返回的迭代器时出现编译错误

c++ - 如何避免 "template parameters not deducible in partial specialization"

c++ - QT QML/C++ 应用程序在退出时崩溃

c++ - 如何在 C++ 中使用类模板声明新运算符

c++ - 在空格处拆分字符串并返回 C++ 中的第一个元素

linux - 如何在 Linux 中用 C++ 检测 SD 卡是否存在

c++ - std::thread 和 std::cin 在 opengl 应用程序中的输入

c++ - 为什么在实现所有模板化类方法之前我们需要 'template <class T>'

c++ - 用于确定类是否输出可流式意外输出的元程序