如何检查类型具有constexpr构造函数
我希望我的班级使用其他实现类型没有ConstexPR构造函数。
这样:
template <typename A>
class foo
{
public:
// if A has constexpr constructor
constexpr foo() :_flag(true) { _data._a = A(); }
// else
constexpr foo() : _flag(false) { _data.x = 0; }
~foo(){}
bool _flag;
union _data_t
{
_data_t() {} // nothing, because it's just an example
~_data_t() {}
A _a;
int x;
}_data;
};
为了实现标题所说的内容,我尝试了:
template<typename _t, _t = _t()>
constexpr bool f()
{
return true;
}
template<typename _t>
constexpr bool f()
{
return false;
}
它适用于不constexpr构造函数的类型。 但是对于其他类型,它会导致含糊不清的超负荷的编译错误。
那我该如何检查呢?
I want my class use another implementation for types don't have constexpr constructor.
like this:
template <typename A>
class foo
{
public:
// if A has constexpr constructor
constexpr foo() :_flag(true) { _data._a = A(); }
// else
constexpr foo() : _flag(false) { _data.x = 0; }
~foo(){}
bool _flag;
union _data_t
{
_data_t() {} // nothing, because it's just an example
~_data_t() {}
A _a;
int x;
}_data;
};
To achieve what the title says, I try this:
template<typename _t, _t = _t()>
constexpr bool f()
{
return true;
}
template<typename _t>
constexpr bool f()
{
return false;
}
It works well for types haven't constexpr constructor.
But for other types it causes a compile error with ambiguous overloads.
so how can I check?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将Sfinae与逗号运算符的功能一起使用
我想您可以在想法之后
,您可以将
f()
函数重写如下。 )对于第二个模板参数,f()
才能在t {}
可以构造时才启用(逗号运算符的功率)(因为代码>(t {},0)是模板参数的参数),否则Sfinae擦除了f()的第一个版本
。并观察到
f()的拳头版本
接收未使用的int
,其中第二个接收long
。这样,第一个版本是首选的,如果可用,请使用int
来调用f()
;当第一个不可用时,选择第二个总比没有解决方案要好(当第一个模板参数不是constexpr默认构造时)。现在,您可以根据
foo
构建两个模板构造函数或不是constexpr构造的以下是一个完整的编译示例(C ++ 14或更新,但您可以为C ++ 11进行修改):
I suppose you can use SFINAE together with the power of the comma operator
Following your idea, you can rewrite your
f()
functions as followsObserve the trick:
int = (T{}, 0)
for the second template argumentThis way
f()
is enabled (power of the comma operator) only ifT{}
can be constexpr constructed (because(T{}, 0)
is the argument for a template parameter), otherwise SFINAE wipe away the first version off()
.And observe that the fist version of
f()
receive an unusedint
where the second one receive along
. This way the first version is preferred, when available, callingf()
with anint
; the second one is selected, as better than nothing solution, when the first one is unavailable (when the first template argument isn't constexpr default constructible).Now you can construct two template constructors for
foo
that you can alternatively enable/disable according the fact the template parameterT
(defaulted toA
) is or isn't constexpr constructibleThe following is a full compiling example (C++14 or newer, but you can modify it for C++11):