方便的 constexpr 函数
Convenient constexpr-function
我可以编写一个执行类型推断但不使用传递给它的对象constexpr
函数:
template <int N>
struct Foo
{
static const int value = N;
};
template <typename T>
constexpr int get_value(T const &)
{
return T::value;
}
void huey()
{
Foo<3> three;
static_assert(get_value(three) == 3, ":(");
}
但是,如果要get_value
参数是某些其他操作的结果,则此方法将失败:
template <int N>
Foo<N + 1> increase(Foo<N> const &)
{
return {};
}
void dewey()
{
Foo<6> six;
static_assert(get_value(increase(six)) == 7, ":(");
}
编译器(正确地)抱怨increase(six)
不是常量表达式。我可以这样解决这个问题:
template <typename T>
constexpr int get_value2()
{
return T::value;
}
void louie()
{
Foo<4> four;
static_assert(get_value2<decltype(increase(four))>() == 5, ":(");
}
但我不喜欢额外的decltype
——体操。我可以介绍一个宏:
#define GET_VALUE(x) get_value2<decltype(x)>()
但如果可能的话,我想避免宏。有没有办法允许没有宏的方便语法get_value(some_function(some_object))
?
increase()
也需要constexpr
template <int N>
struct Foo
{
static const int value = N;
};
template <typename T>
constexpr int get_value(T const &)
{
return T::value;
}
void huey()
{
Foo<3> three;
static_assert(get_value(three) == 3, ":(");
}
template <int N>
constexpr Foo<N + 1> increase(Foo<N> const &)
{
return {};
}
void dewey()
{
Foo<6> six;
static_assert(get_value(increase(six)) == 7, ":(");
}
相关文章:
- 条件constexpr函数
- constexpr 函数中的非文字(通过 std::is_constant_evaluated)
- constexpr构造函数需要常量成员函数时出现问题
- constexpr 函数获取常量字符*
- 如何在 constexpr 函数中实现回退运行时
- 为什么我不能在 constexpr lambda 函数中使用 std::tuple
- 在非 constexpr 函数中作为左值传递的变量上使用 'constexpr' 函数
- 在 constexpr 构造函数 (c++17) 中赋值到 const char * 在使用 Android NDK 时
- NVCC 错误:string_view.h:constexpr 函数返回是非常量
- constexpr函数中的静态constexpr变量
- 在 constexpr funnction 中调用basic_string函数
- 为什么我的 constexpr 对象在我的函数中不是 constexpr?
- constexpr log10 整数函数
- C++:初始化 constexpr 构造函数中的成员数组
- 编译器生成的默认构造函数具有 constexpr 混淆行为
- 在 constexpr 构造函数中初始化数组是否合法?
- 在 constexpr 函数中断言
- MSVC 和函数参数的 constexpr?
- 具有位域的结构的 Constexpr 构造函数
- C++ 默认构造函数 constexpr 或正确未定义