在没有函数调用的情况下确定std::array返回类型的大小

我有一个类B,它将类A作为模板参数。

template<typename T>
class B{
///...

每个T都有一个operator()()返回一个std::array<double, N>。我希望每个专业B<T>都能够在N没有额外要求的情况下推断Ts 并且无需调用operator()(). 我怎样才能做到这一点?

T下面是一个示例并标记为class A

template <int N>
class A {
public:
    A() {}

    std::array<double, N> operator()() {
        std::array<double, N> the_integers;
        for (int i = 0; i < N; ++i) {
            the_integers[i] = i;
        }
        return the_integers;
    }
};

回答

您可以将成员添加到B,就像这样

static constexpr std::size_t ArraySize = std::tuple_size_v<decltype(std::declval<T&>()())>;

这是一个演示

  • Yes, if you make it constexpr, it won't compile. If you don't, it will a have runtime impact. I wonder why `array::size` isn't a static function.
  • @cigien not really. If `operator()` of type `T` returns something that does not have a constexpr constructor, like `array<string, 42>`, it won't be constexpr https://gcc.godbolt.org/z/jr73qhTdn

以上是在没有函数调用的情况下确定std::array返回类型的大小的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>