如何使用 sfinae 选择构造函数?

2021-12-30 00:00:00 constructor c++ c++11 sfinae

在模板元编程中,可以在返回类型上使用SFINAE来选择某个模板成员函数,即

In template meta programming, one can use SFINAE on the return type to choose a certain template member function, i.e.

template<int N> struct A {
  int sum() const noexcept
  { return _sum<N-1>(); }
private:
  int _data[N];
  template<int I> typename std::enable_if< I,int>::type _sum() const noexcept
  { return _sum<I-1>() + _data[I]; }
  template<int I> typename std::enable_if<!I,int>::type _sum() const noexcept
  { return _data[I]; }
};

但是,这不适用于构造函数.假设,我想声明构造函数

However, this doesn't work on constructors. Suppose, I want to declare the constructor

template<int N> struct A {
   /* ... */
   template<int otherN>
   explicit(A<otherN> const&); // only sensible if otherN >= N
};

但不允许 otherN <N.

那么,可以在这里使用 SFINAE 吗?我只对允许自动模板参数推导的解决方案感兴趣,所以

So, can SFINAE be used here? I'm only interested in solutions which allow automatic template-parameter deduction, so that

A<4> a4{};
A<5> a5{};
A<6> a6{a4};  // doesn't compile
A<3> a3{a5};  // compiles and automatically finds the correct constructor

注意:这是一个非常简化的示例,其中 SFINAE 可能有点矫枉过正,而 static_assert 可能就足够了.但是,我想知道我是否可以改用 SFINAE.

Note: this is a very simplified example where SFINAE may be overkill and static_assert may suffice. However, I want to know whether I can use SFINAE instead.

推荐答案

您可以向模板添加默认类型参数:

You can add a defaulted type argument to the template:

template <int otherN, typename = typename std::enable_if<otherN >= N>::type>
explicit A(A<otherN> const &);

相关文章