我正在尝试将 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 ...
我改变了什么:
- 使用
is_same<foo,bar>::value
, 不是is_same<foo,bar>{}
编辑: 嗯,看来您毕竟不需要更改它。整洁! - 在使用
mixin<derived>
时,不试图让编译器推导出派生的模板参数。 .你在那里方式太乐观了...
关于c++ - 使用具有部分类特化的 CRTP?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50670878/