且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

关于模板参数的SFINAE +嵌套类的外部定义

更新时间:2022-10-16 17:46:54

我自己回答,我解决了这个问题,将enable_if检查从模板参数列表移动到构造函数,一切正常,如下所示:

 template< typename T> 
类A {
公共:
A(标准:: initializer_list&LT;类型名的std :: enable_if&LT;的std :: is_arithmetic&LT; T&GT; ::值,T&GT; ::类型→1){ }
class I;
};

模板< typename T>
A类< T> :: I {
public:
int prova(){return 1; };
};


Hi all,
I have a class A, templated with a type T and an enable_if clause, which contains a nested class I (which is meant to be a user-defined iterator for A), like this:

template <typename T, std::enable_if_t<std::is_arithmetic<T>::value>>
class A {
   public:
      class I;
};



I can't find the proper way to defined I outside of A, I understand the error messages (see "What have you tried?" session) I get but what I miss is which is the correct way to do what I want..

What I have tried:

I tried this:

template <typename T, std::enable_if_t<std::is_arithmetic<T>::value>>
class A<T>::I {

};


but it gives the error

Quote:

cannot add a default template argument to the definition of a member of a class template



while this:

template <typename T>
class A<T>::I {

};


gives this error:

Quote:

too few template parameters in template redeclaration

I answer myself, I solved this moving the enable_if check from the template parameters list to the constructor and everything works fine, like this:
template <typename T>
class A {
   public:
      A(std::initializer_list<typename std::enable_if<std::is_arithmetic<T>::value,T>::type> l) {}
      class I;
};

template <typename T>
class A<T>::I {
   public:
      int prova() { return 1; };
};