将非constexpr对象的静态constexpr成员变量用作模板参数

问题描述 投票:0回答:2

我正在编写一个库,其中使用非类型模板参数将本质上是静态的对象参数内置到类型中。在这些值是运行时值(以10倍测得的小型基准,预期5-7倍测得)的实现上,这样做可以提供[[massive性能优化。但是,我发现C ++不能很好地支持这种习惯用法。我正在尝试重构该库,以使对模板或元编程不太熟悉的开发人员可以更轻松地使用它。

我想提供constexpr函数,以简化static constexpr成员变量(用于通过类型传播静态值)的提取,以便用户执行一些基本的元编程,而无需了解幕后的繁琐操作。 。例如,

#include <type_traits> template <int A, int B> class Example { public: static constexpr auto C = A + B; private: int b {0}; }; template <int A, int B> constexpr auto getC(Example<A, B> e) { return decltype(e)::C; } /**** USER CODE ****/ int main() { Example<1, 2> e; Example<2, getC(e)> f; }

这不起作用,即使您不使用该值,也可以在constexpr上下文中使用作为非constexpr的e(奇怪的是,如果Example没有运行时成员,它将起作用)。可以改写decltype(e)::C,但是如果要作为参考,他们将不得不使用std::remove_reference<decltype(C)>::type::C,当然他们也必须知道这样做,并且足够了解如何解决remove_reference调用等常见问题。在这一点上,对于该库适用于的典型程序员,我们已经不熟悉了。

[constexpr]函数不起作用,宏不适用于类型系统,因此它们也不足够,我还能怎么做?

c++ templates constexpr
2个回答
0
投票
您可以使用宏来包装

std::remove_reference<decltype(C)>::type::C

看起来像

#define getC(obj) std::remove_reference_t<decltype(obj)>::C


0
投票
getC()的类型而不是e传递给e怎么办?

我的意思是>

template <typename T> constexpr auto getC () { return T::C; } // ... Example<1, 2> e; Example<2, getC<decltype(e)>()> f;

© www.soinside.com 2019 - 2024. All rights reserved.