Bri*_*ick 3 c++ templates class
我有一些代码大量使用模板类.此时可能但不希望更改现有代码库.我需要编写一个新的类,它将作用于两个模板类(为了这个问题的目的)是任意的,除了有一个共同的模板参数.一个简化的例子:
template<typename T>
class A {
// Implementation details
};
template<typename T>
class B {
// Implementation details
};
template<typename T, typename X<T>, typename Y<T>> // This syntax is invalid!
class C {
// Implementation details
};
Run Code Online (Sandbox Code Playgroud)
我需要写课C.示例中显示的语法暗示了我想要做什么但不起作用.模板参数X和Y这里必须通过采用相同的模板参数"捆绑在一起" T.除此之外,它们可以是任意的.
这意味着"喜欢"的东西C<std::string,A<std::string>,B<std::string>>应该是有效的,但C<std::string,A<std::string>,B<std::map>>不应该因为A并且B没有相同的模板参数.(引号中的"like"再次表示语法在C上面的声明中仍然是错误的.)
其他尝试(也失败了)包括:
template<typename T, template<typename> class X<T>, template<typename> class Y<T>>template<typename T> template<typename X<T>, typename Y<T>>有可能这样吗?如果是这样,语法是什么?
谢谢!
你可以部分专业化C:
//Primary template
template<typename T, typename X, typename Y>
class C;
//Specialization for when the template parameters are the same
template<typename T, template <typename> class X, template <typename> class Y>
class C <T, X<T>, Y<T>> {
// Implementation details
};
Run Code Online (Sandbox Code Playgroud)
如果然后使用无效的模板参数,则会出现编译时错误.