因此,我知道您可以使用enable_if来禁用函数模板(例如,如果类型不是整型的话)--但是,您能对constexpr做同样的操作吗?
也就是说,是否有类似的情况:
template<class T, typename = std::enable_if_t<std::is_integral_v<T>> >
T test2()
{
return {};
}
和警察-就像:
template <typename T>
T test()
{
// we expect various integral and floating point
我现在正在学习如何使用static_assert。到目前为止,我学到的是,static_assert的论点必须是常量表达式。对于下面的代码,我不知道为什么参数reference不是常量表达式:它被声明为const,并由整数常数0初始化
int main()
{
const int &reference = 0;
static_assert(reference);
}
gcc的错误消息指出,reference不能在常量表达式中使用:
error: 'reference' is not usable in a constant expression.
是否
假设我有以下课程:
class A
{
public:
int index;
int init(int type);
}
int A::init(int type)
{
Interface* interface = SelectInterface(type);
int index = interface->get_index(type);
delete interface;
}
然后我有了以下界面:
// ----------- INTERFACES -------------- //
class Interface
{
我对“原子约束”一章很好奇
上面写着
替换后E的类型必须完全是bool。不允许转换
和
f(0); // error: S<int>{} does not have type bool when checking #1,
// even though #2 is a better match
唉哟。这意味着在使用要求条款时没有?这不是一个令人沮丧的吗?
因为我可以看到某些模板类型在遍历表达式后是如何导致bool的,而不是其他模板类型。现在我们又需要使用enable_if之类的东西了。很痛吗?
假设我有一个整数: unsigned long long int data = 4599331010119547059; 现在,我想将此数据转换为双精度型。我基本上想改变类型,但要保持原样。对于给定的示例,浮点值为0.31415926536。 我如何在C++中做到这一点?我看到了一些使用Union的方法,但许多人建议不要使用这种方法。
我有以下代码:
template<auto... args> struct Custom
{
};
int main()
{
Custom<1, nullptr> s; // i want this to succeed only when all the template arguments are of the same type
}
从上面的代码可以看出,我可以传递不同类型的模板参数。我的问题是,是否有一种方法只接受相同类型的模板参数。这意味着,main中的语句应该失败,并且只在所有模板参数都是相同类型时才能工作。实质上,有两项要求:
对于少于
我有一个奇怪的警告是由clang 12.0.1报告的。在以下代码中:
#include <vector>
int main()
{
std::vector<int> v1;
const auto a = v1.begin() + v1.size();
return 0;
}
我看到这一警告被触发:
error: narrowing conversion from 'std::vector<int>::size_type' (aka 'unsigned long long') to signed t
当试图用static_assert作为参数计算逗号运算符时,编译失败
void fvoid() {}
int main() {
int a = (1, 2); // a=2
int b = (fvoid(), 3); // b=3
int d = ( , 5);
// ^
// error: expected primary-expression before ',' token. OK
int c = (static_assert(true), 4);
// ^~~~~~~~~~~~~
如果一个人
template <class T>
class A{};
// global namespace, static storage duration
static constexpr A<int> a;
是否可以通过将A<int>作为引用模板param传递a类型,如:
// This question asks to make the syntax in the following line compile:
static_assert(std::is_same<A<int>, typename GetReferenceTyp