How to ensure template function can be processed during compile time

IGotD- nise at nise.com
Wed Jul 8 20:11:05 UTC 2020


I have the following functions in C++

template<typename T>
inline constexpr size_t mySize(const T &v)
{
     return sizeof(v) + 42;
}


template<typename T>
inline constexpr size_t mySize()
{
     return sizeof(T) + 42;
}

The constexpr ensures that it will be calculated to a compile 
time constant otherwise the build will fail. In this case C++ can 
handle that I feed these functions with both a type and a 
variable which it can solve during compile time.

int v;

constexpr size_t sz = mySize(v);       // works, returns 46
constexpr size_t sz2 = mySize<int>();  // works, returns 46


Doing the same in D, would with my lack of knowledge look like 
this.


size_t mySize(T)()
{
     return T.sizeof + 42;
}


size_t mySize(T)(const T t)
{
      return T.sizeof + 42;
}



int v;

enum sz = mySize!int // works, returns 46
enum sz2 = mySize(v) // doesn't work. Error: variable v cannot be 
read at compile time

Here we have a difference between C++ and D as C++ was able infer 
the size of v during compile time.

Now since mySize is a template, shouldn't this work mySize!v, but 
it doesn't? What essential understanding have I missed here?



More information about the Digitalmars-d-learn mailing list