Struct expression parameter vs. type parameter - d

I'm making an input range to iterate over a custom container that holds data points that need to remain accurately paired as inputs and targets. I need different Ranges for returning training data (double[][]), inputs (double[]) and the targets (also double[]). I managed to get the following code to compile and work perfectly, but I don't know why.
public struct DataRange(string type)
if( type == "TrainingData" ||
type == "InputData" ||
type == "TargetData" )
{
private immutable(int) length;
private uint next;
private Data data;
this(Data d){
this.length = d.numPoints;
this.next = 0;
this.data = d;
}
#property bool empty(){return next == length;}
#property auto front(){
static if(type == "TrainingData")
return this.data.getTrainingData(next);
else static if(type == "InputData")
return this.data.getInputData(next);
else return this.data.getTargetData(next);
}
void popFront(){++next;}
}
static assert(isInputRange!(DataRange!"TrainingData"));
static assert(isInputRange!(DataRange!"InputData"));
static assert(isInputRange!(DataRange!"TargetData"));
I've been reading the "The D Programming Language" by Alexandrescu, and I have found parameterized structs of the form
struct S(T){...} // or
struct S(T[]){...}
but these take type parameters, not expressions like I've done. I haven't been able to find any similar examples on dlang.org with parameterized types.
This compiles and works on DMD 2.066 and GDC 4.9.0.
I don't even know why I tried this, and looking back at it I don't know why it works. Anybody know what I'm missing? Where is this documented?

Ok, I found the answer. Though this wasn't specifically mentioned or described in any of the tutorials or anywhere in the book, I was eventually able to find it at http://dlang.org.template.html. Basically there are two things going on here.
1.) Though my code says struct, this is really a template (that results in a struct). I have seen examples of this online and in the book, though it wasn't described as a template. It was a bit confusing because I didn't use the template keyword, and in the book they are described as "parameterized."
2.) From the website linked above...
Template parameters can be types, values, symbols, or tuples
So in my case my template parameter was a symbol. The examples in the book used types.
Digging into the language specifications on the website reveals there is a lot more going on than is covered in the book!

Alternatively you could use an enum to simplify the constraint in such a way that a wrong template instantiation is impossible (even if in your code the template constraint does it perfectly). example:
enum rangeKind{training, input, target};
public struct DataRange(rangeKind Kind)
{
}
void main(string args[])
{
DataRange!(rangeKind.training) dr;
}

Related

static_assert inside template or class, gotcha

On this subject, I have read few relevant SO questions/answers/comments. Found only one relevant but somewhat buried question/answer here. Allow me to try and clearly show the issue in question/answer manner. For the benefit of others.
Let the code speak. imagine you design this template.
// value holder V1.0
// T must not be reference or array or both
template<typename T> struct no_arrf_naive
{
static_assert(!std::is_reference_v<T>, "\n\nNo references!\n\n");
static_assert(!std::is_array_v<T>, "\n\nNo arrays!\n\n");
using value_type = T;
T value;
};
Simple and safe, one might think. Some time after, other folks take this complex large API, where this is buried deep, and start using it. The struct above is deep inside. As usually, they just use it, without looking into the code behind.
using arf = int(&)[3];
using naivete = no_arrf_naive<arf>;
// the "test" works
constexpr bool is_ok_type = std::is_class_v< naivete >;
// this declaration will also "work"
void important ( naivete ) ;
But. Instantiations do not work
naivete no_compile;
static assert message does show all of a sudden. But how has the "test" compiled and passed? What is going on here?
The issue is that API is wrong. static_assert as class member does "kick-in" but not before instantiation.
First the offending API commented
template<typename T>
struct no_arrf_naive
{
// member declarations
// used only on implicit instantiation
// https://en.cppreference.com/w/cpp/language/class_template#Implicit_instantiation
static_assert(!std::is_reference_v<T>, "\n\nNo references!\n\n");
static_assert(!std::is_array_v<T>, "\n\nNo arrays!\n\n");
using value_type = T;
T value;
};
Users are here properly coding to transform from Template to Type, but, static_assert's do not kick-in:
using naivete = no_arrf_naive<arf>;
This might most worryingly go on unnoticed, until someone wants to use this. That will not compile and the message, API author has placed in there, will show at last. But alas, too late.
And on projects laboring on some large C++ source, problems that show up late, are the most notorious ones.
The solution is good old SFINAE. The API fixed is this:
// value holder
// references or arrays or both are excluded at compile time
template<typename T,
std::enable_if_t<
(!std::is_reference_v<T> && !std::is_array_v<T>), bool> = true
> struct no_arrf
{
using value_type = T;
T value;
};
The above will not compile immediately upon trying to create the type from template with either reference or array or both:
// reference to array of three int's
using arf = int(&)[3] ;
// no can do
using no_naivete = no_arrf<arf>;
(MSVC) error C2972: 'no_arrf':
template parameter 'unnamed-parameter':
the type of non-type argument is invalid
I might think this whole story might look like trivial or even useless to some. But, I am sure many good folks are coming to SO for badly needed standard C++ advice. For them, this is neither trivial nor useless.
Many thanks for reading.

Handle errors C++

So, I have a simple library-class and this class has some methods that return some values like code errors.
User_program
MyClass go(arg1, arg2)
if(go.execute() == 0)
std::cout << go.result();
And my class has something like this
My class
int execute()
{
if((temp = doBar()) != 0)
{
return temp;
}
return SUCCESS;
}
int doBar()
{
if(foo == 1)
return DIVIDION_BY_ZERO;
if(fzz == 0)
return OPERATION_ERROR;
}
And so on. So, is there any method to make errors more helpful, I've heard about enum with const for errors, but I don't understand how to implement it.
Thanks.
Not sure that I understood the question right, but here is few moments.
In your case enum`s is way to store all definitions of const
values like (SUCCESS, DIVIDION_BY_ZERO, etc) in one place (even in
one translation unit). And also compiletime validation of types.
read more here:
[1]
2) If intresting how implemented some error check there is no need
to go far.
First of all look at C handling errors in libc [2]
In ISO C++11 presented [system_error]
And typical error handling in libs released special for (almost) each type like in Qt [QNetworkReply]
And also using exceptions(and dark side of C++ like RTTI) in libs is bad idea. But take this link too [3]

How would you use Alexandrescu's Expected<T> with void functions?

So I ran across this (IMHO) very nice idea of using a composite structure of a return value and an exception - Expected<T>. It overcomes many shortcomings of the traditional methods of error handling (exceptions, error codes).
See the Andrei Alexandrescu's talk (Systematic Error Handling in C++) and its slides.
The exceptions and error codes have basically the same usage scenarios with functions that return something and the ones that don't. Expected<T>, on the other hand, seems to be targeted only at functions that return values.
So, my questions are:
Have any of you tried Expected<T> in practice?
How would you apply this idiom to functions returning nothing (that is, void functions)?
Update:
I guess I should clarify my question. The Expected<void> specialization makes sense, but I'm more interested in how it would be used - the consistent usage idiom. The implementation itself is secondary (and easy).
For example, Alexandrescu gives this example (a bit edited):
string s = readline();
auto x = parseInt(s).get(); // throw on error
auto y = parseInt(s); // won’t throw
if (!y.valid()) {
// ...
}
This code is "clean" in a way that it just flows naturally. We need the value - we get it. However, with expected<void> one would have to capture the returned variable and perform some operation on it (like .throwIfError() or something), which is not as elegant. And obviously, .get() doesn't make sense with void.
So, what would your code look like if you had another function, say toUpper(s), which modifies the string in-place and has no return value?
Have any of you tried Expected; in practice?
It's quite natural, I used it even before I saw this talk.
How would you apply this idiom to functions returning nothing (that is, void functions)?
The form presented in the slides has some subtle implications:
The exception is bound to the value.
It's ok to handle the exception as you wish.
If the value ignored for some reasons, the exception is suppressed.
This does not hold if you have expected<void>, because since nobody is interested in the void value the exception is always ignored. I would force this as I would force reading from expected<T> in Alexandrescus class, with assertions and an explicit suppress member function. Rethrowing the exception from the destructor is not allowed for good reasons, so it has to be done with assertions.
template <typename T> struct expected;
#ifdef NDEBUG // no asserts
template <> class expected<void> {
std::exception_ptr spam;
public:
template <typename E>
expected(E const& e) : spam(std::make_exception_ptr(e)) {}
expected(expected&& o) : spam(std::move(o.spam)) {}
expected() : spam() {}
bool valid() const { return !spam; }
void get() const { if (!valid()) std::rethrow_exception(spam); }
void suppress() {}
};
#else // with asserts, check if return value is checked
// if all assertions do succeed, the other code is also correct
// note: do NOT write "assert(expected.valid());"
template <> class expected<void> {
std::exception_ptr spam;
mutable std::atomic_bool read; // threadsafe
public:
template <typename E>
expected(E const& e) : spam(std::make_exception_ptr(e)), read(false) {}
expected(expected&& o) : spam(std::move(o.spam)), read(o.read.load()) {}
expected() : spam(), read(false) {}
bool valid() const { read=true; return !spam; }
void get() const { if (!valid()) std::rethrow_exception(spam); }
void suppress() { read=true; }
~expected() { assert(read); }
};
#endif
expected<void> calculate(int i)
{
if (!i) return std::invalid_argument("i must be non-null");
return {};
}
int main()
{
calculate(0).suppress(); // suppressing must be explicit
if (!calculate(1).valid())
return 1;
calculate(5); // assert fails
}
Even though it might appear new for someone focused solely on C-ish languages, to those of us who had a taste of languages supporting sum-types, it's not.
For example, in Haskell you have:
data Maybe a = Nothing | Just a
data Either a b = Left a | Right b
Where the | reads or and the first element (Nothing, Just, Left, Right) is just a "tag". Essentially sum-types are just discriminating unions.
Here, you would have Expected<T> be something like: Either T Exception with a specialization for Expected<void> which is akin to Maybe Exception.
Like Matthieu M. said, this is something relatively new to C++, but nothing new for many functional languages.
I would like to add my 2 cents here: part of the difficulties and differences are can be found, in my opinion, in the "procedural vs. functional" approach. And I would like to use Scala (because I am familiar both with Scala and C++, and I feel it has a facility (Option) which is closer to Expected<T>) to illustrate this distinction.
In Scala you have Option[T], which is either Some(t) or None.
In particular, it is also possible to have Option[Unit], which is morally equivalent to Expected<void>.
In Scala, the usage pattern is very similar and built around 2 functions: isDefined() and get(). But it also have a "map()" function.
I like to think of "map" as the functional equivalent of "isDefined + get":
if (opt.isDefined)
opt.get.doSomething
becomes
val res = opt.map(t => t.doSomething)
"propagating" the option to the result
I think that here, in this functional style of using and composing options, lies the answer to your question:
So, what would your code look like if you had another function, say toUpper(s), which modifies the string in-place and has no return value?
Personally, I would NOT modify the string in place, or at least I will not return nothing. I see Expected<T> as a "functional" concept, that need a functional pattern to work well: toUpper(s) would need to either return a new string, or return itself after modification:
auto s = toUpper(s);
s.get(); ...
or, with a Scala-like map
val finalS = toUpper(s).map(upperS => upperS.someOtherManipulation)
if you don't want to follow a functional route, you can just use isDefined/valid and write your code in a more procedural way:
auto s = toUpper(s);
if (s.valid())
....
If you follow this route (maybe because you need to), there is a "void vs. unit" point to make: historically, void was not considered a type, but "no type" (void foo() was considered alike a Pascal procedure). Unit (as used in functional languages) is more seen as a type meaning "a computation". So returning a Option[Unit] does make more sense, being see as "a computation that optionally did something". And in Expected<void>, void assumes a similar meaning: a computation that, when it does work as intended (where there are no exceptional cases), just ends (returning nothing). At least, IMO!
So, using Expected or Option[Unit] could be seen as computations that maybe produced a result, or maybe not. Chaining them will prove it difficult:
auto c1 = doSomething(s); //do something on s, either succeed or fail
if (c1.valid()) {
auto c2 = doSomethingElse(s); //do something on s, either succeed or fail
if (c2.valid()) {
...
Not very clean.
Map in Scala makes it a little bit cleaner
doSomething(s) //do something on s, either succeed or fail
.map(_ => doSomethingElse(s) //do something on s, either succeed or fail
.map(_ => ...)
Which is better, but still far from ideal. Here, the Maybe monad clearly wins... but that's another story..
I've been pondering the same question since I've watched this video. And so far I didn't find any convincing argument for having Expected, for me it looks ridiculous and against clarity&cleanness. I have come up with the following so far:
Expected is good since it has either value or exceptions, we not forced to use try{}catch() for every function which is throwable. So use it for every throwing function which has return value
Every function that doesn't throw should be marked with noexcept. Every.
Every function that returns nothing and not marked as noexcept should be wrapped by try{}catch{}
If those statements hold then we have self-documented easy to use interfaces with only one drawback: we don't know what exceptions could be thrown without peeking into implementation details.
Expected impose some overheads to the code since if you have some exception in the guts of your class implementation(e.g. deep inside private methods) then you should catch it in your interface method and return Expected. While I think it is quite tolerable for the methods which have a notion for returning something I believe it brings mess and clutter to the methods which by design have no return value. Besides for me it is quite unnatural to return thing from something that is not supposed to return anything.
It should be handled with compiler diagnostics. Many compilers already emit warning diagnostics based on expected usages of certain standard library constructs. They should issue a warning for ignoring an expected<void>.

C++ Function Pointer

Is this possible? If so, I can't seem to get the syntax right. (C++ function pointer)
bit of background. The code below has been shorten for this post. The reason for this implementation is to avoid an endless list of SWITCH/CASE or IF/ELSEIF statements; and have an endless list of DECODER_FUNCTION_TABLE (see below). This code deals with an industry standard that uses mnemonics to mean different things and there are hundreds of these mnemonics. So this portion of my code is to decode certain mnemonics pass to it from another section of code that loops through a passed in record... anyway my difficulty is in keeping a member function pointer in a structure outside of the class...
Have a look. I think the code may do a better job explaining ;)
typedef struct _DECODER_FUNCTION_RECS
{
ISO_MNEMONIC_ID Mnemonic;
void (Database::*pFn)(Database::Rec *);
}DECODER_FUNCTION_RECS;
DECODER_FUNCTION_RECS DECODER_FUNCTION_TABLE[] = {
SFP, &Database::Decode_SFP,
KOG, &Database::Decode_KOG
};
void Database::DecodedDescription(Rec *A)
{
int i = 0;
bool Found = false;
while( i < DECODER_FUNCTION_TABLE_COUNT && !Found )
{
if( DECODER_FUNCTION_TABLE[i].Mnemonic == A->Mnemonic )
Found = true;
else
i++;
}
if( Found )
(([DECODER_FUNCTION_TABLE[i]).*this.*pFn)( A );
}
void Database::Decode_SFP(Rec *A)
{
// do decode stuff on A
}
The detail I'm trying to work out is this line:
(([DECODER_FUNCTION_TABLE[i]).*this.*pFn)( A );
You call a member function pointer (that's what it's called) with
(this->*DECODER_FUNCTION_TABLE[i].pFn)(A);
Could put parens around DECODER_FUNCTION_TABLE[i].pFn, but the member access operator . has a higher precedence than member function operator ->*.
I wrote up a few simple examples that will shed some light the other day
It's in my answer to this question
error C2664 and C2597 in OpenGL and DevIL in C++
Or a direct link to codepad

Syntax for std::binary_function usage

I'm a newbie at using the STL Algorithms and am currently stuck on a syntax error. My overall goal of this is to filter the source list like you would using Linq in c#. There may be other ways to do this in C++, but I need to understand how to use algorithms.
My user-defined function object to use as my function adapter is
struct is_Selected_Source : public std::binary_function<SOURCE_DATA *, SOURCE_TYPE, bool>
{
bool operator()(SOURCE_DATA * test, SOURCE_TYPE ref)const
{
if (ref == SOURCE_All)
return true;
return test->Value == ref;
}
};
And in my main program, I'm using as follows -
typedef std::list<SOURCE_DATA *> LIST;
LIST; *localList = new LIST;;
LIST* msg = GLOBAL_DATA->MessageList;
SOURCE_TYPE _filter_Msgs_Source = SOURCE_TYPE::SOURCE_All;
std::remove_copy(msg->begin(), msg->end(), localList->begin(),
std::bind1st(is_Selected_Source<SOURCE_DATA*, SOURCE_TYPE>(), _filter_Msgs_Source));
What I'm getting the following error in Rad Studio 2010. The error means "Your source file used a typedef symbol where a variable should appear in an expression. "
"E2108 Improper use of typedef 'is_Selected_Source'"
Edit -
After doing more experimentation in VS2010, which has better compiler diagnostics, I found the problem is that the definition of remove_copy only allows uniary functions. I change the function to uniary and got it to work.
(This is only relevant if you didn't accidentally omit some of your code from the question, and may not address the exact problem you're having)
You're using is_Selected_Source as a template even though you didn't define it as one. The last line in the 2nd code snippet should read std::bind1st(is_Selected_Source()...
Or perhaps you did want to use it as a template, in which case you need to add a template declaration to the struct.
template<typename SOURCE_DATA, typename SOURCE_TYPE>
struct is_Selected_Source : public std::binary_function<SOURCE_DATA *, SOURCE_TYPE, bool>
{
// ...
};
At a guess (though it's only a guess) the problem is that std::remove_copy expects a value, but you're supplying a predicate. To use a predicate, you want to use std::remove_copy_if (and then you'll want to heed #Cogwheel's answer).
I'd also note that:
LIST; *localList = new LIST;;
Looks wrong -- I'd guess you intended:
LIST *locallist = new LIST;
instead.