c ++ std :: enable_if [英] c++ std::enable_if
问题描述
我对std :: enable_if很陌生,想知道如何使用它。
我有一个模板类:
I am quite new to std::enable_if and wondering how to use it. I have a template class:
template<int a, int b>
class foo {
}
现在我只想实例化它+ b等于10.
我可以使用std :: enable_if吗?
Now I only want to instantiate it when a + b equals to 10. Could I make this possible using std::enable_if?
第二个问题:
如果我有一个成员class foo
The second question: If I have a member in class foo
template<int a, int b>
class foo {
int c;
}
我只想在
a = 5.
我这样做使用std :: enable_if?
这是正确的case使用std :: enable_if?
How do I do that using std::enable_if? Is this one the correct case to use std::enable_if?
推荐答案
我想你可以使用static_assert更好强制执行该约束,而不是enable_if
I guess you can use static_assert better to enforce that constraint instead of enable_if
template<int a, int b>
class foo {
static_assert(a+b==10, "a+b is not 10");
};
int main()
{
foo<5,5> f; // will compile
foo<1,5> f; // will fail to compile with error: a+b is not 10
return 0;
}
enable_if主要用于有条件地从基于类型的重载分辨率中删除函数和类并为不同类型的特性提供单独的函数重载和特化。
enable_if is primarily used to conditionally remove functions and classes from overload resolution based on type traits and to provide separate function overloads and specializations for different type traits.
这篇关于c ++ std :: enable_if的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!