0

Consider following trivial example with a simple Test class with operator() which is constexpr. Even if test is not defined with constexpr keyword it may be used to yield size of an std::array during compile time. What is the reason behind such behaviour? Is this well defined in C++?

#include <array> struct Test { constexpr int operator()(int i) const { return i * 2; } }; int main() { Test test{}; std::array<int, test(10)> arr{}; } 

On the other hand following does not compile:

struct Test { int member; constexpr Test(int member): member(member) {} constexpr int operator()(int i) const { return i * member; } }; int main() { /* constexpr */ Test test{10}; std::array<int, test(10)> arr{}; } 

In this case we need explicit constexpr in order to compile the code.

5
  • 1
    Related: stackoverflow.com/q/32803708 Commented Jul 26, 2023 at 13:32
  • Well, in the first example, the operator() doesn't depend on any member of the struct. But in the second example, the function depend on the variable 'member'. And when you declare a static array, you need a const value for the size. Well, if your function wouldn't be constexpr and would depend on the member variable, it wouldn't be a const value Commented Jul 26, 2023 at 13:35
  • ` std::array<int, test(10)> arr{};` wll use the operator()(int i); and so that must be a constant expression which means test must be a constant expression to and thus you need a constexpr instance of test. (some slight syntax inprovements will also show intent a bit better on when you mean calling the operator or the constructor) See : godbolt.org/z/KW5E5xhaM (always make your constructors with one argument explicit) Commented Jul 26, 2023 at 13:39
  • @PepijnKramer yeah, but why the former snippet does not require the constexpr keyword as we also need to have a test instance in order to invoke the method :) Commented Jul 26, 2023 at 13:45
  • 1
    Informally it's quite easy to understand. You'are able to change member at runtime, hence your operator does not always produce a constexpr result, but template arg must be constexpr Commented Jul 26, 2023 at 13:55

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.