问题描述
假设我有这些声明
template<typename T> class User;
template<typename T> class Data;
并希望实现 User<>
T = Data< some_type>
以及从 Data< some_type>
and want to implement User<>
for T = Data<some_type>
and any class derived from Data<some_type>
but also allow for other specialisations defined elsewhere.
如果我还没有类模板的声明 User<>
,我可以简单地
If I didn't already have the declaration of the class template User<>
, I could simply
template<typename T,
typename A= typename std::enable_if<is_Data<T>::value>::type>
class User { /*...*/ };
其中
template<template<typename> data>> struct is_Data
{ static const bool value = /* some magic here (not the question) */; };
但是,这有两个模板参数,因此与上一个声明冲突,用户<>
仅使用一个模板参数声明。还有什么我可以做吗?
However, this has two template parameters and thus clashes with the previous declaration, where User<>
is declared with only one template parameter. Is there anything else I can do?
(注意
template<typename T,
typename A= typename std::enable_if<is_Data<T>::value>::type>
class User<T> { /*...*/ };
无效(默认模板参数不能用于部分特殊化) ,
以及
doesn't work (default template arguments may not be used in partial specializations),nor does
template<typename T> class User<Data<T>> { /*...*/ };
,因为它不允许从 ;>
,
template<typename T>
class User<typename std::enable_if<is_Data<T>::value,T>::type>
{ /*...*/ };
$ b
since template parameter T
is not used in partial specialization.)
推荐答案
如果,原始声明 User<>
适用于
template<typename, typename=std::true_type> class User;
然后我们可以找到一个解决方案(按照Luc Danton的注释,而不是使用)
then we can find a solution (following Luc Danton's comment, instead of using std::enable_if
)
template<typename>
struct is_Data : std::false_type {};
template<typename T>
struct is_Data<Data<T>> : std::true_type {};
template<typename T>
class User<T, typename is_Data<T>::type >
{ /* ... */ };
但是,此不回答原始问题以更改 User
的原始定义。我仍然在等待更好的答案。这可能是一个结论性的,表明没有其他解决方案是可能的。
However, this doesn't answer the original question, since it requires to change the original definition of User
. I'm still waiting for a better answer. This could be one that conclusively demonstrates that no other solution is possible.
这篇关于使用SFINAE进行模板类专门化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!