I have a simple array wrapper class, which goes like this:
class MyArray
{
int * m_Data;
int m_Size;
public:
MyArray(int aSize) : m_Size(aSize), m_Data(new int[aSize])
{
}
int & operator [](int aIndex)
{
return m_Data[aIndex];
}
const int & operator [](int aIndex) const
{
return m_Data[aIndex];
}
};
MyArray a(10);
Whenever I try to evaluate a subscript operator in the debugger (quick watch, immediate window etc): e.g. a[0], I get a[0] no operator "[]" matches these operands error. I know I can dig through class fields to get to the content of the array. But it is so much easier to just copy a part of code line and evaluate it in the watch window.
I tried removing const and non-const [] operators. I also tried using () operator, it didn't work either, but it gave a different error message. I tried this in VS2012 and VS2013 Preview: same thing.
Is there any way to fix this?
If I replace the subscript operator with a member function:
int & Item(int aIndex)
{
return m_Data[aIndex];
}
Then watch window is able to show me the result. But I would prefer to use subscript operator.
I found a solution, which is not very convenient, but seems to work. If I use the expanded form of the operator call, then it works in VC++2012:
a.operator[](0)
It's not clear to me why these two forms are different to VC++ debugger. So I posted a new question here
Related
I'm trying to do a quick rewrite of our codebase to replace all instances of new T(...) with New<T>(...) (a custom function), so I can do some local measurements.
I think clang-tidy is the way to go here, so I've made a small clang tidy script, based off of this tutorial I found. The script is able to run, but not pass tests, since I do not match things correctly.
However, I'm running into problems getting the type out of the matched new expression.
What I have so far is:
class ReplaceNewAndDeleteCheck : public utils::TransformerClangTidyCheck {
public:
ReplaceNewAndDeleteCheck(StringRef Name, ClangTidyContext *Context)
: TransformerClangTidyCheck(MakeRules(), Name, Context) {}
};
Where MakeRules is defined as follows:
RewriteRuleWith<std::string> MakeRules() {
std::string s = "new";
return makeRule(
cxxNewExpr().bind(s),
changeTo(cat("New<", node(s), ">")),
cat("")
);
}
The script is able to run, but does not give the correct result. For example, with int* x = new int(10);, what I want is int* x = New<int>(10);, but what I get is int* x = New<new int(10)>;.
I know MakeRules is wrong, since I'm binding the entire new expression, not just the on the entire but I can't figure out how to either get the type and arguments out of the new expression, or to bind to those instead.
Following code in MSVC generates warning about assignment in conditional expression.
https://godbolt.org/z/i_rwY9
int main()
{
int a;
if ((a = 5)) {
return 1;
}
return a;
}
Note that I tried to use the double () around if since that makes the warning go away with g++, but I do not know how to make it go away in msvc without extracting the assignment from condition.
Is there a way to nudge msvc to figure out that this assignment is intentional?
I know I can use pragmas to disable this warning, but pattern is very common so I would like to get a solution without pragmas if one exists.
The MSVC compiler will give this warning unless you can convince it that you really do know what you're doing. Adding at least one 'real' logical test will achieve this:
int main()
{
int a;
if ((a = 5) != 0) {
return 1;
}
return a;
}
Note that the constant 5 can readily be replaced with any variable or valid expression: adding the explicit != 0 test does nothing to actually change the outcome of the code (and it is unlikely to change the generated assembly).
Ok, so I'm using C++ to make a library that'd help me to print lines into a console.
So, I want to override " "(quote operators) to create an std::string instead of the string literal, to make it easier for me to append other data types to that string I want to output.
I've seen this done before in the wxWidgets with their wxString, but I have no idea how I can do that myself.
Is that possible and how would I go about doing it?
I've already tried using this code, but with no luck:
class PString{
std::string operator""(const char* text, std::size_t len) {
return std::string(text, len);
}
};
I get this error:
error: expected suffix identifier
std::string operator""(const char* text, std::size_t len) {
^~
which, I'd assume, want me to add a suffix after the "", but I don't want that. I want to only use ""(quotes).
Thanks!
You can't use "" without defining a suffix. "" is a const char* by itself either with a prefix (like L"", u"", U"", u8"", R"()") or followed by suffixes like (""s, ""sv, ...) which can be overloaded.
The way that wxString works is set and implicit constructor wxString::wxString(const char*); so that when you pass "some string" into a function it is essentially the same as wxString("some string").
Overriding operator ""X yields string literals as the other answer.
First of I have 2 Classes in 2 files (both .h and .cpp files), Create.h and AI.h.
Create.h has this struct in it:
public:
struct Cell
{
//some stuff
vector<Cell*> neighbors;
State state;
};
Here is the enum class State (stored in the Create.h file):
enum class State : char
{
//some states like "empty"
};
Now in AI.cpp I have a function like this:
void AI::Function(Create::Cell cell)
{
for each (Create::Cell* var in cell.neighbors)
{
if (var->state == State::empty)
{
}
}
}
So basically I am trying to access each individual Cell which is stored in cell.neighbors with a for each so I can do some stuff to each one of them.
According to my debugger though it doesn't even reach the if (var->state == State::empty) part. Am I using the for each wrong?
EDIT: The neighbors vector has definitely elements in it
If you are compiling with optimizations enabled, then an empty if statement like that might be completely removed (it has no side-effects).
(Although, I think the debugger won't let you set a breakpoint on that line, if it were removed. So this is an easy test -- try to set a breakpoint on the if itself.)
it seems that the vector is empty. You can check this printing its size before the loop.
And I would like to answer some comments. This form of the for loop is MS VC++ language extension. It is not C++/CLI.
I'm new to D, and I was wondering whether it's possible to conveniently do compile-time-checked duck typing.
For instance, I'd like to define a set of methods, and require that those methods be defined for the type that's being passed into a function. It's slightly different from interface in D because I wouldn't have to declare that "type X implements interface Y" anywhere - the methods would just be found, or compilation would fail. Also, it would be good to allow this to happen on any type, not just structs and classes. The only resource I could find was this email thread, which suggests that the following approach would be a decent way to do this:
void process(T)(T s)
if( __traits(hasMember, T, "shittyNameThatProbablyGetsRefactored"))
// and presumably something to check the signature of that method
{
writeln("normal processing");
}
... and suggests that you could make it into a library call Implements so that the following would be possible:
struct Interface {
bool foo(int, float);
static void boo(float);
...
}
static assert (Implements!(S, Interface));
struct S {
bool foo(int i, float f) { ... }
static void boo(float f) { ... }
...
}
void process(T)(T s) if (Implements!(T, Interface)) { ... }
Is is possible to do this for functions which are not defined in a class or struct? Are there other/new ways to do it? Has anything similar been done?
Obviously, this set of constraints is similar to Go's type system. I'm not trying to start any flame wars - I'm just using D in a way that Go would also work well for.
This is actually a very common thing to do in D. It's how ranges work. For instance, the most basic type of range - the input range - must have 3 functions:
bool empty(); //Whether the range is empty
T front(); // Get the first element in the range
void popFront(); //pop the first element off of the range
Templated functions then use std.range.isInputRange to check whether a type is a valid range. For instance, the most basic overload of std.algorithm.find looks like
R find(alias pred = "a == b", R, E)(R haystack, E needle)
if (isInputRange!R &&
is(typeof(binaryFun!pred(haystack.front, needle)) : bool))
{ ... }
isInputRange!R is true if R is a valid input range, and is(typeof(binaryFun!pred(haystack.front, needle)) : bool) is true if pred accepts haystack.front and needle and returns a type which is implicitly convertible to bool. So, this overload is based entirely on static duck typing.
As for isInputRange itself, it looks something like
template isInputRange(R)
{
enum bool isInputRange = is(typeof(
{
R r = void; // can define a range object
if (r.empty) {} // can test for empty
r.popFront(); // can invoke popFront()
auto h = r.front; // can get the front of the range
}));
}
It's an eponymous template, so when it's used, it gets replaced with the symbol with its name, which in this case is an enum of type bool. And that bool is true if the type of the expression is non-void. typeof(x) results in void if the expression is invalid; otherwise, it's the type of the expression x. And is(y) results in true if y is non-void. So, isInputRange will end up being true if the code in the typeof expression compiles, and false otherwise.
The expression in isInputRange verifies that you can declare a variable of type R, that R has a member (be it a function, variable, or whatever) named empty which can be used in a condition, that R has a function named popFront which takes no arguments, and that R has a member front which returns a value. This is the API expected of an input range, and the expression inside of typeof will compile if R follows that API, and therefore, isInputRange will be true for that type. Otherwise, it will be false.
D's standard library has quite a few such eponymous templates (typically called traits) and makes heavy use of them in its template constraints. std.traits in particular has quite a few of them. So, if you want more examples of how such traits are written, you can look in there (though some of them are fairly complicated). The internals of such traits are not always particularly pretty, but they do encapsulate the duck typing tests nicely so that template constraints are much cleaner and more understandable (they'd be much, much uglier if such tests were inserted in them directly).
So, that's the normal approach for static duck typing in D. It does take a bit of practice to figure out how to write them well, but that's the standard way to do it, and it works. There have been people who have suggested trying to come up with something similar to your Implements!(S, Interface) suggestion, but nothing has really come of that of yet, and such an approach would actually be less flexible, making it ill-suited for a lot of traits (though it could certainly be made to work with basic ones). Regardless, the approach that I've described here is currently the standard way to do it.
Also, if you don't know much about ranges, I'd suggest reading this.
Implements!(S, Interface) is possible but did not get enough attention to get into standard library or get better language support. Probably if I won't be the only one telling it is the way to go for duck typing, we will have a chance to have it :)
Proof of concept implementation to tinker around:
http://dpaste.1azy.net/6d8f2dc4
import std.traits;
bool Implements(T, Interface)()
if (is(Interface == interface))
{
foreach (method; __traits(allMembers, Interface))
{
foreach (compareTo; MemberFunctionsTuple!(Interface, method))
{
bool found = false;
static if ( !hasMember!(T, method) )
{
pragma(msg, T, " has no member ", method);
return false;
}
else
{
foreach (compareWhat; __traits(getOverloads, T, method))
{
if (is(typeof(compareTo) == typeof(compareWhat)))
{
found = true;
break;
}
}
if (!found)
{
return false;
}
}
}
}
return true;
}
interface Test
{
bool foo(int, double);
void boo();
}
struct Tested
{
bool foo(int, double);
// void boo();
}
pragma(msg, Implements!(Tested, Test)());
void main()
{
}