如何应用使默认构造函数有条件地显式
How can I apply make a default constructor conditionally explicit?
>问题
假设我们有一个(虚构的(类模板C<T>
,其中包含一个有条件显式的默认构造函数。默认构造函数应该是显式的,当且仅当 std::is_same_v<T, int>
.
搜索"[c++] 有条件显式"将返回以下结果:构造函数有条件地标记为显式。
失败的解决方案
接受的答案给出了一个例子:
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() {}
};
不幸的是,这甚至没有编译:演示
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。
问题
- 为什么这不编译?
- 什么是可能的实现?
如果可能的话,我想避免专门上课。
- 什么是可能的实现?
你试过吗
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() {}
};
?
- 为什么这不编译?
问题在于,在类方法之上,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
进行测试,能够启用/禁用构造函数。
相关文章:
- 有一个构造函数,但有两个析构函数
- 有条件地启用类C++构造函数
- 错误:在“(”标记之前进行预期的构造函数、析构函数或类型转换.即使我有一个构造函数
- 如何应用使默认构造函数有条件地显式
- std::initializer_list 是否有复制构造函数,是否曾经使用过?
- 为什么编译器在有模板构造函数时生成复制/移动构造函数
- 有条件地实例化具有删除默认构造函数的类
- std::shared_ptr<X> 有复制构造函数吗?
- 为什么有一个构造函数同时接受initializer_list和一个参数包
- 我有一个构造函数,但我需要将输出返回到 main.cpp.我无法使用获取字符串功能!!任何想法如何实现这一目标?
- 指针有复制构造函数吗
- 有一个构造函数块是可以接受的样式吗
- 当我给有复制构造函数但没有赋值运算符的对象赋值时会发生什么
- 不同的类模式:条件构造函数/方法与继承
- c++结构体是否有默认构造函数?
- 模板类:没有合适的默认构造函数可用.但是我的一些类不能有默认构造函数
- 当返回一个用带括号的init列表初始化的对象时,我保证有一对构造函数和析构函数调用吗?
- 为什么std::函数实例有默认构造函数?
- 没有合适的默认构造函数可用,尽管有默认构造函数
- 是否必须有默认构造函数才能在c++中使用统一初始化