【发布时间】:2018-06-03 20:53:21
【问题描述】:
我正在尝试将 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 子句中重新指定模板参数吗?
【问题讨论】:
-
如果你的 mixin 只是在 U 上模板化的方法,为什么还需要在 T 上模板化?
-
我没有把它放在这里,但我需要降级回基类,这让我很头疼......
标签: c++ c++11 templates template-meta-programming