www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Testing template parameter has given API

reply NaN <divide by.zero> writes:
Howdy, any idea what Im doing wrong? Given a type T i want to 
test the presence of certain methods. I looked in phobos to see 
how isInputRange was defined but it didnt really help as all the 
methods have no parameters and it used some weird lamda stuff i 
think.


template isPathType(T)
{
     alias FloatType = ReturnType!(T.x);

     enum isPathType = (isFloatOrDouble!(FloatType)
         && (is(typeof(&T.x) == FloatType delegate(size_t idx)))
         && (is(typeof(&T.y) == FloatType delegate(size_t idx)))
         && (is(typeof(&T.cmd) == PathCmd delegate(size_t idx)))
         && (is(typeof(&T.points) == Point!FloatType 
delegate(size_t idx)))
         && (is(typeof(&T.length) == size_t delegate())));
}
May 15 2020
next sibling parent Adam D. Ruppe <destructionator gmail.com> writes:
try changing delegate to function, on the type itself it is often 
function
May 15 2020
prev sibling parent reply Paul Backus <snarwin gmail.com> writes:
On Saturday, 16 May 2020 at 01:11:54 UTC, NaN wrote:
 Howdy, any idea what Im doing wrong? Given a type T i want to 
 test the presence of certain methods. I looked in phobos to see 
 how isInputRange was defined but it didnt really help as all 
 the methods have no parameters and it used some weird lamda 
 stuff i think.


 template isPathType(T)
 {
     alias FloatType = ReturnType!(T.x);

     enum isPathType = (isFloatOrDouble!(FloatType)
         && (is(typeof(&T.x) == FloatType delegate(size_t idx)))
         && (is(typeof(&T.y) == FloatType delegate(size_t idx)))
         && (is(typeof(&T.cmd) == PathCmd delegate(size_t idx)))
         && (is(typeof(&T.points) == Point!FloatType 
 delegate(size_t idx)))
         && (is(typeof(&T.length) == size_t delegate())));
 }
Rather than trying to inspect the function itself, it's easier to check that the result of *calling* the function is what you expect it to be. So, for example: is(typeof(T.x(size_t.init)) == FloatType) The above checks to see whether, when you call T.x with a size_t argument, you get a FloatType back. If you write your checks this way, it doesn't matter whether T.x is a function, a delegate, or even a template.
May 15 2020
parent NaN <divide by.zero> writes:
On Saturday, 16 May 2020 at 02:02:47 UTC, Paul Backus wrote:
 On Saturday, 16 May 2020 at 01:11:54 UTC, NaN wrote:

 Rather than trying to inspect the function itself, it's easier 
 to check that the result of *calling* the function is what you 
 expect it to be. So, for example:

     is(typeof(T.x(size_t.init)) == FloatType)

 The above checks to see whether, when you call T.x with a 
 size_t argument, you get a FloatType back. If you write your 
 checks this way, it doesn't matter whether T.x is a function, a 
 delegate, or even a template.
That fixed it. Thanks.
May 16 2020