如何避免“部分专业化无法推导的模板参数”

时间:2019-02-25 12:52:23

标签: c++ c++11 templates nested

我想使用模板访问嵌套类,但不知道该怎么做:示例代码:

template <typename T> class mything {
  typedef unsigned key;
  T data;
public:
  template <typename subT> class mysubthing { typedef subT value_type; };
  using subthing = mysubthing<T>;
  using subthing_ro = mysubthing<const T>;
};

template<typename T> struct X; // a container for all value_types

#ifdef MAKE_IT_FAIL
// this should automatically set the X<mything<T>::mysubthing<subT>
template<typename T,typename subT> struct X<typename mything<T>::template mysubthing<subT>> {
  using value_type = subT;
};
#endif

typedef mything<int> intthing;

#ifndef MAKE_IT_FAIL
template<> struct X<mything<int>::subthing> { using value_type = int; };
template<> struct X<mything<int>::subthing_ro> { using value_type = const int; };
#endif

int main(void) {
  intthing t;
  X<intthing::subthing>::value_type data = 1; // a data object
  X<intthing::subthing_ro>::value_type data_ro = 1; // read-only data object

  return 0;
}

该编译器不带-DMAKE_IT_FAIL进行编译,但是由于我要手动输入,因此它完全错过了有关模板的要点。如何使其与-DMAKE_IT_FAIL一起使用?

1 个答案:

答案 0 :(得分:1)

您不能那样专长:

template<typename T,typename subT> 
struct X<typename mything<T>::template mysubthing<subT>> {

因为在C ++中不可能(不支持)从outer<T>::anything_after之类的类型中减去T。

在这种一般情况下,您实际上根本不需要专业化。只需定义默认的X,然后仅专门处理其他情况:

template <typename T> class mything {
  typedef unsigned key;
  T data;
public:
  template <typename subT> struct mysubthing 
  { 
      typedef subT value_type; 

  };
  using subthing = mysubthing<T>;
  using subthing_ro = mysubthing<const T>;
};

template<typename T> struct X
{
   using value_type = typename T::value_type;
};
// this should automatically set the X<mything<T>::mysubthing<subT>

typedef mything<int> intthing;

template<> struct X<mything<int>::subthing> { using value_type = int; };
template<> struct X<mything<int>::subthing_ro> { using value_type = const int; };

int main(void) {
  intthing t;
  X<intthing::subthing>::value_type data = 1; // a data object
  X<intthing::subthing_ro>::value_type data_ro = 1; // read-only data object

  return 0;
}

附录

根据其中一个注释,X实际上是std::iterator_traits,已经定义。在这种情况下,唯一的解决方法是在神话类之外定义迭代器类:

template <typename T, typename subT>
class mything_iterator {
   typedef subT value_type; 
};
template <typename T> class mything {
      typedef unsigned key;
      T data;
    public:
      using iterator = mything_iterator<T, T>;
      using const_iterator = mything_iterator<T, const T>;
};
namespace std {
   template<typename T, class subT>
   class iterator_traits<mything_iterator<T, subT>>{
       using value_type =typename  mything_iterator<T, subT>::value_type;
       // etc...
   };
   template<> struct iterator_traits<mything<int>::iterator>
   { using value_type = int; };
   template<> struct iterator_traits<mything<int>::const_iterator>
   { using value_type = int; };
}