0
我可以写一个constexpr
函数执行类型推演但不使用传递给它的对象:方便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
-gymnastics。我可以引入一个宏:
#define GET_VALUE(x) get_value2<decltype(x)>()
但我想避免宏,如果可能的话。有没有任何方法可以让没有宏的方便的语法get_value(some_function(some_object))
?
什么是错的'模板 constexpr富增加(富常量&)'? –