如何应用make有条件显式的默认构造函数?

问题描述 投票:2回答:1

问题

假设我们有一个(虚构的)类模板C<T>,带有条件显式的默认构造函数。当且仅当std::is_same_v<T, int>时,默认构造函数应该是显式的。

A search on "[c++] conditionally explicit"返回此结果:Constructor conditionally marked explicit

失败的解决方案

接受的答案给出了一个例子:

struct S {
  template <typename T,
             typename std::enable_if<std::is_integral<T>::value, bool>::type = false >
  S(T) {}

  template <typename T,
            typename std::enable_if<!std::is_integral<T>::value, bool>::type = false>
  explicit S(T) {}
};

稍微修改这个例子给出了这个实现,它使用了std::enable_if熟悉的方法:

template <class T>
class C {
public:
  template <std::enable_if_t<std::is_same_v<T, int>, int> = 0>
  C() {}

  template <std::enable_if_t<!std::is_same_v<T, int>, int> = 0>
  explicit C() {}
};

不幸的是,这甚至没有编译:demo

prog.cc: In instantiation of 'class C<int>':
prog.cc:15:10:   required from here
prog.cc:10:12: error: no type named 'type' in 'struct std::enable_if<false, int>'
   10 |   explicit C() {}
      |            ^
prog.cc: In instantiation of 'class C<double>':
prog.cc:18:13:   required from here
prog.cc:7:3: error: no type named 'type' in 'struct std::enable_if<false, int>'
    7 |   C() {}
      |   ^

问题似乎是由于省略了构造函数的模板参数,导致SFINAE失效。

  1. 为什么这不编译?
  2. 什么是可能的实施?

如果可能的话,我想避免专门的课程。

c++ templates template-meta-programming sfinae explicit
1个回答
2
投票
  1. 什么是可能的实施?

你试过吗?

template <class T>
class C {
public: //  VVVVVVVVVVVVVV .................................V  U here, not T
  template <typename U = T, std::enable_if_t<std::is_same_v<U, int>, int> = 0>
  C() {}

  template <typename U = T, std::enable_if_t<!std::is_same_v<U, int>, int> = 0>
  explicit C() {}
};

?

  1. 为什么这不编译?

问题是SFINAE,类方法,与方法本身的模板参数一起使用。

这是在原始的工作代码中:

  template <typename T,
             typename std::enable_if<std::is_integral<T>::value, bool>::type = false >
  S(T) {}

其中T是特定于构造函数的模板参数(从单个参数推导出)。

相反,在你的失败代码中,

template <std::enable_if_t<std::is_same_v<T, int>, int> = 0>
C() {}

构造函数正在评估类的模板参数(T),而不是方法。

使用技巧typename U = T,你转换T,类的模板参数,在U,方法的模板参数(在你的情况下构造函数,但也适用于其他方法)所以std::enable_if_t,测试取决于U,能够启用/禁用构造函数。

© www.soinside.com 2019 - 2024. All rights reserved.