Formatting C++ Header Files in Visual Studio [on hold] - c++

Is there any extension out there or option to format c++ header files in specific way?
Say we have this header file:
class SomeClass
{
public:
int m_iMember1;
std::string m_sMember2;
std::map<int, std::vector<std::string>> m_someLongMember;
protected:
int m_iMember3;
private:
std::string m_sMember4;
public:
void Function1();
std::string Function2();
SomeClass() = default;
protected:
std::map<int, std::vector<std::string>> Function3();
private:
bool IsThereAnyWayOfDoingThis;
};
And the way I want the header to be:
class SomeClass
{
public:
int m_iMember1;
std::string m_sMember2;
std::map<int, std::vector<std::string>> m_someLongMember;
protected:
int m_iMember3;
private:
std::string m_sMember4;
public:
void Function1();
std::string Function2();
SomeClass() = default;
protected:
std::map<int, std::vector<std::string>> Function3();
private:
bool IsThereAnyWayOfDoingThis;
};
I'm using resharper plugin and with resharper I can CTRL + ENTER and choose Format Selection.
Visual Studio also have build in code formatting. But is there a way configuring it's behavior? Or anyone aware of any extension to do this for us?
Thanks for the answers!

With ReSharper, you can always check what formatting preferences affect a block of code. Just select a code snippet, hit Alt+Enter, and choose Format Selection -> Configure.... ReSharper will show a dialog where you can change formatting options and instantly see how this affects the formatting style.
In this case you need to enable Indentation and Alignment | Align Similar Code In Columns | Declaration names. It won't work however across accessibility specifiers. Please also note that it's a relatively new feature, available in ReSharper 2017.3 and later.

Related

D.R.Y vs “avoid macros”

I am creating my own implementation of XUL in C++ using the Windows API. The fact that the elements are constructed by the XML parser requires that they have identical interfaces, so that we don't need to write custom code for each element constructor. The result is that most of my elements look like this:
class Button : public Element
{
public:
static const char * Type() { return "button"; }
private:
friend class Element;
Button(Element * inParent, const AttributesMapping & inAttributesMapping);
};
class Label : public Element
{
public:
static const char * Type() { return "label"; }
private:
friend class Element;
Label(Element * inParent, const AttributesMapping & inAttributesMapping);
};
class Description : public Element
{
public:
static const char * Type() { return "description"; }
virtual bool init();
private:
friend class Element;
Description(Element * inParent, const AttributesMapping & inAttributesMapping);
};
So there is a lot of code duplication here. I wonder if it would be a good idea to replace them with macro calls like this:
#define DECLARE_ELEMENT(ElementType, XULName) \
class ElementType : public Element \
{ \
public: \
static const char * Type() { return XULName; } \
\
private: \
friend class Element; \
ElementType( \
Element * inParent, \
const AttributesMapping & inAttributesMapping); \
}; \
DECLARE_ELEMENT(Window, "window")
DECLARE_ELEMENT(Button, "button")
DECLARE_ELEMENT(Label, "label")
I haven't completely worked out the concept yet, so a few things are missing here, like the class definitions, and (maybe) the ability to add methods per element.
But I'd like to know your opinion of using macros in this situation. Feel free to share your thoughts.
EDIT
I am now using a small ruby script that generates the source and header files from a set of templates. I enhanced the scripts so that the files are also automatically marked for addition on SVN, and the Visual Studio project file is modified to include the files. This saves me a lot of manual labor. I'm quite happy with this solution. FYI this is what the templates look like now:
#ifndef {{ELEMENT_NAME_UPPER}}_H_INCLUDED
#define {{ELEMENT_NAME_UPPER}}_H_INCLUDED
#include "XULWin/Element.h"
namespace XULWin
{
class {{ELEMENT_NAME}} : public Element
{
public:
static ElementPtr Create(Element * inParent, const AttributesMapping & inAttr)
{ return Element::Create<{{ELEMENT_NAME}}>(inParent, inAttr); }
static const char * Type() { return "{{ELEMENT_TYPE}}"; }
virtual bool init();
private:
friend class Element;
{{ELEMENT_NAME}}(Element * inParent, const AttributesMapping & inAttributesMapping);
};
} // namespace XULWin
#endif // {{ELEMENT_NAME_UPPER}}_H_INCLUDED
CPP document:
#include "XULWin/{{ELEMENT_NAME}}.h"
#include "XULWin/{{ELEMENT_NAME}}Impl.h"
#include "XULWin/AttributeController.h"
#include "XULWin/Decorator.h"
namespace XULWin
{
{{ELEMENT_NAME}}::{{ELEMENT_NAME}}(Element * inParent, const AttributesMapping & inAttributesMapping) :
Element({{ELEMENT_NAME}}::Type(),
inParent,
new {{ELEMENT_NAME}}Impl(inParent->impl(), inAttributesMapping))
{
}
bool {{ELEMENT_NAME}}::init()
{
return Element::init();
}
} // namespace XULWin
I would not use a macro here. The clue is in your class "Description", which has an extra member function init, which the others don't. So you wouldn't be able to use the macro to define it, but you'd instead expand the macro manually and add the extra line.
To me, this is a bigger violation of DRY than just writing out all the class definitions. Almost not repeating yourself, but doing it just for one case, often ends up harder to maintain that repeating yourself consistently. DRY is about finding good abstractions, not just cutting down on boilerplate.
I might replace those constructors, though, with a SetAttributes function in class Element. That might cut the amount of boilerplate actually required in each derived class, since constructors are the one thing that can't be inherited from the base. But it depends how similar the implementations are of the constructor of each class.
If you use a template solution, you can avoid macros and avoid repeating yourself:
template <const char *XULName>
class ElementType : public Element
{
public:
static const char * Type() { return XULName; }
private:
friend class Element;
ElementType(
Element * inParent,
const AttributesMapping & inAttributesMapping);
};
char windowStr[]="window";
char buttonStr[]="button";
char labelStr[]="label";
typedef ElementType<windowStr> Window;
typedef ElementType<buttonStr> Button;
typedef ElementType<labelStr> Label;
Rule of thumb: Templates can be used for just about everything that macros were necessary for in C.
Implementation note: String literals can't be used directly as template arguments because they have internal linkage -- that's why you need the windowStr etc. In practice, you would want to put the declarations of windowStr, buttonStr and labelStr in the H file and the definitions of those strings in a CPP file.
As an alternative, you might consider generating the code an a separate build step, instead of using the preprocessor. I like cog, But you could use whatever you like -- This way you get full programmatic control over what is generated. (Macros are powerful, but limited in what you can do.)
I think macros can be okay to reduce repetition (and thus, the risk of introducing errors) at a low level like this.
The use of macros will remain very localized, and should make the code as a whole easier to understand. Of course it might require some documentation effort too.
Use whatever makes the code simpler.
DRY and Avoid Macro both have the same goal: making your code simpler.
DRY: avoid repetition
Avoid Macro: because they can introduce hard to diagnose compiler errors or hard to diagnose bugs (as they bypass namespace boundaries and are not C++ aware / typesafe).
As usual with the guidelines, I would thus suggest to follow the spirit rather than the letter. In your case it appears evident that the macro will actually simplify your code, so you should probably use it.
However, taking into account the problems that a macro may introduce, make sure to name it 'safely'. Include the project name / file name at the beginning for example to reduce the potential 'clash' with an existing macro.
(you can take a look at BOOST header guards to have an idea of naming convention)
Be wary of using macros that replace class definitions if you plan on using automatic code documentation tools like doxygen. You'll have to run the code through the preprocessor before generating any documentation. Not, perhaps, the most important consideration, but something to consider nonetheless.
IMHO this macro is justified. Although I think it would be better to add #undef DECLARE_ELEMENT to prevent dangling macros. (Unless you plan to use this macro in other files as well.)
Note however that this will work only if those classes will never differ much (or best at all).
There is yet another solution using templates. Consider following code
namespace impl
{
struct ButtonTag;
struct LabelTag;
template< typename TypeTag >
struct NameGenerator;
template<>
struct NameGenerator< ButtonTag >
{
static const char * getName() { return "button"; }
};
template<>
struct NameGenerator< LabelTag >
{
static const char * getName() { return "label"; }
};
template< typename TypeTag >
class SimpleElement : public Element
{
public:
static const char * Type()
{ return NameGenerator< TagType >::getName(); }
private:
friend class Element;
SimpleElement(
Element * inParent,
const AttributesMapping & inAttributesMapping);
};
}
typedef impl::SimpleElement< impl::ButtonTag > Button;
typedef impl::SimpleElement< impl::LabelTag > Label;
It is somewhat more verbose however avoids macros.
code samples
enum Types { BUTTON, LABEL,...}
struct TypeList {
static const char * Type(const int nID)
{
switch(nID) {
case BUTTON: return "button";
...
}
};
template<ID>
class IElem : public Element
{
private:
static TypeList m_oTypeList;
public:
static const char * Type() { return m_oTypeList.Type(ID); }
private:
friend class Element;
IElem(Element * inParent, const AttributesMapping & inAttributesMapping)
{...}
};
for non-common functions and specialized
class Button : public IElem<BUTTON>
{
...
}
I could even go a bit further and use both the single hash and double hash feature when using macros. Single hash create string constants and the double concatenate identifiers to build new combined.
#define DECLARE_ELEMENT(ElementType) \
class C ## ElementType : public Element \
{ \
public: \
static const char * Type() { return # ElementType; } \
\
private: \
friend class Element; \
C ## ElementType( \
Element * inParent, \
const AttributesMapping & inAttributesMapping); \
}
DECLARE_ELEMENT(window); // defines Cwindow
DECLARE_ELEMENT(button); // defines Cbutton
DECLARE_ELEMENT(label); // defines Clabel
For instance the below code is something I sometimes write to test the sizeof for some common types.
#include <stdio.h>
#define OUT( _type ) printf("sizeof(%s) = %d\n", #_type, sizeof(_type))
int main() {
OUT( char );
OUT( int );
OUT( short );
OUT( long );
OUT( long long );
OUT( void* );
return 0;
}
I would vote for macros in this case. They aren't that bad after all, you shouldn't try to write inline functions with them but other than that they are good.
I think the use of macros is okay in this case, but only if you
can develop a solution that is not too complex but covers (preferably) all necessary Element class structures
document the macro well
are aware that some IDEs have problems with macro-generated class structures and can live with the consequences
This code looks an awful lot like the program that Tom Cargill dissects and reassembles in Chapter 1 of his book "C++ Programming Style", dating back to 1992. Admittedly, that code did not use macros to replicate the almost identical classes, but the net result looks awfully similar from out here.

Visual Assist (Visual studio 2013) auto-suggestion not applying (TAB)

I'm not sure which hotkey I triggered, but I seemed to have disabled the TAB key auto typing the suggested code and it's really getting annoying. Does anyone know a fix for this?
For example:
class Class1
{
private:
float Value;
public:
void SetProperty(float Val) { Value = Val; }
};
Class1 Inst = new Class1;
Inst.Se /* <--- TAB here should auto complete, menu pops up but dosen't apply */

Doxygen issue with C++ array initialization

I'm using Doxygen to generate an API for my current project and happened upon some strange behavior. Basically, if I use an initialization list to set a member array in a class's constructor, Doxygen does not produce proper output.
Here's a simple test class:
#ifndef TEST_HPP
#define TEST_HPP
class TestClass {
public:
/** Constructor Version 1 */
TestClass() : v{0,0,0} { }
/** Constructor Version 2 */
// TestClass() {
// v[0] = 0;
// v[1] = 0;
// v[2] = 0;
// }
protected:
/** my little array */
float[3] v;
};
#endif // TEST_HPP
If I run doxygen on the file with Version 1 of the constructor, I get a relatively empty HTML file for the class with no constructor documentation and no mention of my variable v. If I comment out Version 1 and use Version 2, Doxygen properly produces documentation for the class.
I know this type of array setting is new to C++11, but is it the initialization or the fact that it's done in an initialization list? If anyone knows what causes this behavior I'd appreciate it as we use these types of initializers all over the code and I'd like to avoid sweeping changes if necessary.
Doxygen v1.7.6.1 dates back to 10th December 2011. It's old.
C++11 support was fundamentally added in v1.8.2; a bug in this support that seems to cover your case precisely (#688647 "Fixed problem parsing initializer list with C++11 style uniform types") was fixed in v1.8.3.
The changelog is your friend in researching such things.
The solution? Upgrade to acquire updates to Doxygen's C++ parsing abilities.
We're on v1.8.5 these days.
I am using Doxygen 1.8.5 from ARCH/extra, and the problem seems to still exist when it comes to empty initializer lists. Consider:
// not parsed correctly by doxygen 1.8.5
class X
{
public:
typedef std::initializer_list<double> DoublesInitializer;
typedef std::initializer_list<int > IntsInitializer;
X(DoublesInitializer d, IntsInitializer i={}) : d_(d), i_(i) {}
X(IntsInitializer i) : X({},i) {}
private:
const std::list<double> d_;
const std::list<int > i_;
};
This is valid C++11 code, but in the Doxygen html output the appear superfluous „Public Attributes” i and i_, the first without a type, and the second with type const std::list<int>. Doxygen also believes to find „Initial value” for i, which is
{}
private:
const std::list<double> d_
It turns out that the second constructor is the problematic one, since this works correctly:
// parsed correctly by doxygen 1.8.5
class Y
{
public:
typedef std::initializer_list<double> DoublesInitializer;
typedef std::initializer_list<int > IntsInitializer;
Y(DoublesInitializer d, IntsInitializer i={}) : d_(d), i_(i) {}
Y(IntsInitializer i) : Y(DoublesInitializer(),i) {}
private:
const std::list<double> d_;
const std::list<int > i_;
};
If this is indeed a bug, I will re-open #688647.

C++ class for application/program settings?

Using Visual Studio C++ with MFC. I'm trying to figure out what would be a good way to store application/program settings. I'm not referring to their persistent storage but to the data structure used in code to hold the settings.
I created a static class called Settings that has several static methods and also nested classes to partition the settings. For example:
class Settings
{
public:
Settings(void);
~Settings(void);
static void SetConfigFile(const char * path);
static CString GetConfigFilePath();
static void Load();
static void Save();
class General
{
public:
static CString GetHomePage();
static void SetHomePage(const char * url);
private:
static int homePageUrl_;
};
private:
static CString configFilePath_;
};
Then I can access my settings throughout my code like:
Settings::General::GetHomePage();
Now I'm getting into unit testing and I'm starting to realize that static classes are undesirable. So I want to turn this into an instance based class. But I'll have to manage the nested class instances which is trivial but still seems a little cumbersome for testing. The whole intention of the nested classes is simply to group the settings into logical groups. I'm debating whether a string-based settings class would be better, something like settings->get("General.HomePage") although I think I prefer the strong typing of dedicated accessor methods.
So to get to my question what is a good data structure to hold program configuration/settings that supports straightforward unit testing?
You can do this if it works for you. You can ditch the enum and go to const strings or even free-form strings. The enum doesn't really have to be defined in the class either. There are lots of ways to do it.
Another class could do something similar with multiple instances using a template to define the enum type if you wanted to implement categories.
Just an idea.
#include "stdafx.h"
#include <map>
#include <string>
#include <iostream>
using namespace std;
class Settings
{
public:
typedef enum
{
HomePageURL,
EmailAddress,
CellPhone
} SettingName;
private:
typedef map<SettingName, string> SettingCollection;
SettingCollection theSettings;
public:
string& operator[](const SettingName& theName)
{
return theSettings[theName];
}
void Load ()
{
theSettings[HomePageURL] = "http://localhost";
}
void Save ()
{
// Do whatever here
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Settings someSettings;
someSettings.Load ();
cout << someSettings [Settings::SettingName::HomePageURL] << endl;
return 0;
}
I don't think there has to be a conflict between your requirements of: (1) providing type-safe access to configuration variables; and (2) using a "fully.scoped.name" syntax to specify the name of a configuration variable. Surely you could have type-safe operations such as:
const char * getString(const char * fullyScopedName);
int getInt(const char * fullyScopedName);
bool getBool(const char * fullyScopedName);
You might find some inspiration by reading Chapters 2 and 3 of the Getting Started Guide (PDF, HTML) for my Config4Cpp library.
Edit: The Config4Cpp documentation I mentioned might provide inspiration for API design, but I belated realised that you might appreciate advice on implementation options in case you decide to write your own configuration class from scratch (rather than use a third-party library like Config4Cpp) ...
Your class should use a std::map to store a collection of fullyScopedName->value mappings. Obviously, the fullyScopedName will be a string, but there are two options for representing the value.
The first option is to represent the value as a string. A type-safe accessor such as getInt() or getBool() will retrieve the string-based value from the map and then parse it to convert it into the desired type. If the parsing fails, then the accessor operation throws an exception. (That is the approach taken by Config4Cpp.)
The second option is to represent value as shown in the pseudocode below:
enum ValueType { STRING_VAL, INT_VAL, BOOL_VAL };
struct Value {
ValueType type;
union {
const char * stringVal;
int intVal;
bool boolVal;
} data;
};
The implementation of a type-safe accessor can then be coded as follows (pseudocode):
int getInt(const char * fullyScopedName)
{
Value * v = nameValueMap[fullyScopedName];
if (v->type != INT_VAL) {
throw WrongTypeException(...);
}
return v->data.intVal;
}
This is the class that I'm using now mostly inspired by Nathan's answer except with templated methods:
class Settings {
public:
Settings(void);
virtual ~Settings(void);
enum SettingName { General_WindowWidth, General_HomePageUrl,
General_ShowDownloadsWindow, Privacy_RememberPasswords,
Privacy_RememberHistory };
virtual void SetConfigFile(const char * path);
virtual std::string GetConfigFilePath();
virtual void Load();
virtual void Save();
template<class T>
T Get(SettingName name) {
return boost::lexical_cast<T>(settings_[name]);
}
template<class T>
void Set(SettingName name, T value) {
settings_[name] = boost::lexical_cast<std::string>(value);
}
void Set(SettingName name, std::string value) {
settings_[name] = value;
}
private:
std::string configFilePath_;
std::map<SettingName, std::string> settings_;
};

C++ Auto Class Implementation in Editor

Much of my time spent developing C++ applications is wasted implementing class definitions. By that I mean the prototyping of classes then creating their respective implementations.
For example:
#ifndef FOO_H
#define FOO_H
class Foo
{
public:
Foo (const X& x, const Y& Y);
~Foo ();
void PerformXYZ (int Count);
};
#endif
And now I'll have to copy and paste, then add the repetitive Foo:: onto each function.
Foo::Foo (const X& x, const Y& Y)
{
}
Foo::~Foo ()
{
}
void Foo::PerformXYZ (int Count)
{
}
For now I copy the function declarations over to their respective *.cpp files, remove empty lines, then replace ';' with "\n{\n\n}\n". However, I still have to specify the namespace for each function.
Are there tools in Eclipse, Vim or any other IDE/editor that take this burden off a developer?
In Visual Studio there are tools to add functions and variable. Tools automates the process in question. But I never use them :)
In the Visual Assist X there is the feature that helps to add implementation for methods. It is the best solution.
In Visual Studio 2008, you can add a class (it will generate a .h and .cpp file for you) using Project->Add Class... option. But it is very primitive and writes only constructor and destructors. After adding the class, you can go to class view and use 'Add method' menu option to add methods to the class.
Like you, I have long thought my time as a C++ developer is wasted with writing tedious class-definitions. The only tool I have found so far that partly alleviates this druge-work is VisualAssistX, as one of the other posters mentions.
While falling short of completely eliminating the need for writing class definitions, VA X has some nice "refactor" methods that help in this area. For example, you can create a method declaration, and it will automatically create an implementation body for you. You can also do things like "Add similar member", which fills in the "add member" dialog with the data of an existing method or change the signature of a function and have it propagate to both the cpp and h files automatically.
It's not free, but well worth the money.
Jeroen
For vim, I'm maintaining this suite that provides class snippets (which can be easily adapted to your needs).
NB: The generation of each function definition can be automated with the command :GOTOIMPL, but it must be done function after function.
Eclipse surely has something related to this in it's refactoring menu though I haven't used it for a year and don't remember any specifics.
The Zeus editor can be configured to do this using it's template feature as follows.
Step 1: Create a c:\temp\test.tpl file that looks like this:
#ifndef $Word_H
#define $Word_H
class $Word
{
public:
$Word (const X& x, const Y& Y);
~$Word ();
void PerformXYZ (int Count);
};
#endif
$Word::$Word (const X& x, const Y& Y)
{
}
$Word::~$Word ()
{
}
void $Word::PerformXYZ (int Count)
{
}
Step 2: Using the Template, Options menu to add the following template:
$ExpandTemplate<c:\temp\test.tpl>
Step 3: Using the File, New menu, type in the word Bar, place the cursor on the word Bar and run the newly created template and you get this text:
#ifndef Bar_H
#define Bar_H
class Bar
{
public:
Bar (const X& x, const Y& Y);
~Bar ();
void PerformXYZ (int Count);
};
#endif
Bar::Bar (const X& x, const Y& Y)
{
}
Bar::~Bar ()
{
}
void Bar::PerformXYZ (int Count)
{
}

Resources