0
votes

I have a template class which has a variadic constructor that takes specializations of itself. It looks like that (basically):

template<std::size_t SIZE_>
class SomeClass {
public:
    static constexpr std::size_t SIZE = SIZE_;

    template<typename T>
    static constexpr std::size_t computeTotalSize(const T& t) {
        return T::SIZE;
    }

    template <typename T, typename... Ts>
    static constexpr std::size_t computeTotalSize(const T& t, const Ts&... ts) {
        return computeTotalSize(t) + computeTotalSize(ts...);
    }

    SomeClass() = default;

    template <typename T, typename... Ts>
    SomeClass(const T& t, const Ts&... ts) {
        static_assert(computeTotalSize(t, ts...) == SOME_NUMBER, "SOME_MESSAGE");
        // some other stuff
    }
};

Now I try to instantiate SomeClass<SOME_NUMBER>:

SomeClass<SOME_NUMBER> someObject((SomeClass<1>()), (SomeClass<2>()), (SomeClass<3>()));

I get the following errors:

error: constexpr variable 'totalSize' must be initialized by a constant expression
note: function parameter 't' with unknown value cannot be used in a constant expression

I expected this to work fine since I have declared computeTotalSize function as constexpr and the type of all parameters is known at compile time.

I found out that if I call computeTotalSize function directly, it works fine. For example, the following compiles:

constexpr std::size_t totalSize = SomeClass<SOME_NUMBER>::computeTotalSize((SomeClass<1>()), (SomeClass<2>()), (SomeClass<3>()));

Why is it returning a constexpr in the second case only? How can I make it work in the constructor?

1
the constructor is not constexpr - apple apple

1 Answers

1
votes

The problem is that even though the template parameter named T is a constant expression the function parameter named t isn't.

And since t isn't a constant expression it cannot be used in the constexpr context you're trying to use it in as mentioned in the error saying:

function parameter 't' with unknown value cannot be used in a constant expression