我有一个模板化的课程Converter
,我想做一个部分专业化。棘手的部分是我想将它专门化为MyFoo::Vec
,其中MyFoo
可以再次专门用作模板参数。如果这听起来令人困惑,那么代码本身可能会更清楚:
#include <iostream>
#include <vector>
template<class To>
struct Converter {
Converter(int from, To& to) {
to = To(from);
}
};
template<class T>
struct Foo {
typedef std::vector<T> Vec;
Vec vec;
};
// Template specialization: Convert from 'From' to 'MyFoo::Vec':
template<class MyFoo>
struct Converter<typename MyFoo::Vec > { // Error: template parameters not
// used in partial specialization
Converter(int from, typename MyFoo::Vec& to) {
to.push_back(typename MyFoo::Vec::value_type(from));
}
};
int main() {
Foo<float> myfoo;
Converter<Foo<float> > converter(2, myfoo.vec);
}
这只是从我的实际代码派生的一个迷你示例。这个问题不是关于这种转换器有多么有用;我只是想让语法正确,因为我需要这样的转换器及其专业化。
答案 0 :(得分:2)
不能直接完成。考虑到从嵌套类型到封闭类型是不可能的,原因有二:首先,映射可能不是唯一的(多个Foo
可能具有相同的嵌套Vec
类型),即使它是编译器必须测试所有现有类型(即它不能从实例化推断)。
您想要做的事情实际上可以通过SFINAE完成(未经测试的代码,您可以阅读更多here):
template <typename T, typename V = void>
struct Converter {}; // Default implementation
template <typename T>
struct Converter<T, T::Vec> {}; // specific if has nested Vec