Operator++ for nested private enum - which compiler is right? - c++

Basically, what I would like to be able to is to define operator++ for Test enum, which is a private member of a Inner class, which is private member of an Outer class. This snippet might be helpful in understanding what I want to acchieve:
class Outer{
class Inner{
enum Test{ONE, TWO, THREE};
};
};
const Outer::Inner::Test& operator++(Outer::Inner::Test& test){
int rawTest = test;
test = static_cast<Outer::Inner::Test>(++rawTest);
return test;
}
Unfortunately above will not compile with error, that Test is private member, so next I tried following:
#include <iostream>
using namespace std;
class Outer{
class Inner{
enum Test{ONE, TWO, THREE};
friend const Test& operator++(Test& test);
};
friend const Inner::Test& operator++(Inner::Test& test);
};
const Outer::Inner::Test& operator++(Outer::Inner::Test& test){
int rawTest = test;
test = static_cast<Outer::Inner::Test>(++rawTest);
return test;
}
this still does not work, because Test is defined in private Inner class, so I would have to friend both classes together, although there is no point in it (I do not want to access Test enum in Outer class. Just to be able to use operator++ in inner class)
Of course I can make function inline like this:
#include <iostream>
using namespace std;
class Outer{
class Inner{
enum Test{ONE, TWO, THREE};
friend const Test& operator++(Test& test){
int rawTest = test;
test = static_cast<Outer::Inner::Test>(++rawTest);
return test;
}
};
};
, but I might not want this, because of let's say some magical additional logic, which I want to have in .cpp file. How should I declare operator++ properly to be able to operator on Test enum?
EDIT:
This is surely not a duplicate of given question, as I want to simply declare operator++ for given enum in nested class. The provided duplicate question is about accessing member of Inner class from an Outer class function.
EDIT:
Bringing here Holt's comment:
"Actually, clang accepts your second code (with the two friend declaration), which would be the standard way. Whether this is a clang extension or a g++ bug I don't know... Maybe you should reformulate your question to get the attention of some language-lawyer around there ;)" Maybe the more appropriate question would be, whether it is right, that gcc and msvc (which I tried) does not allow double fiendship code, or not, as in my opinion C++ standard should somehow allow clean coding in such cases like this one (in fact not so complicated case).

What you want to declare is a "global" function (operator++) that will only be used inside Outer::Inner due to the access on Test. I don't know if this is possible, but a simple work around would be to fallback to a static method of Inner:
#include <iostream>
class Outer{
class Inner{
enum Test{ONE, TWO, THREE};
static Test& pre_inc(Test&);
friend Test& operator++(Test& test) {
return pre_inc(test);
}
};
};
auto Outer::Inner::pre_inc(Test& test) -> Test& {
int rawTest = test;
test = static_cast<Test>(++rawTest);
return test;
}

Related

Is there a name for the idiom of using a friend class to hide what would have been private functions?

If a class has lots of private functions it seems undesirable to have them declared in the header file. It makes it harder for clients to parse the interface of the class and it increases compilation time.
One option is, of course, the pimpl idiom, but that adds a layer of indirection and also results in a memory allocation.
What follows is a example of hiding helper functions in a friend class that is defined in the implementation file.
Is there a name for this idiom?
Is there any reason not to do it?
//Foo.h
class Foo
{
public:
void FuncA();
void FuncB();
private:
int x;
// more data...
friend struct FooHelpers;
};
//Foo.cpp
struct FooHelpers
{
static void Helper1(Foo& f)
{
// manipulate private data..
f.x++; //etc.
}
// Possibly more funcs...
};
void Foo::FuncA()
{
//....
FooHelpers::Helper1(*this);
//....
}
//....
Is there a name for the idiom of using a friend class to hide what would have been private functions?
The Attorney-Client idiom.
Is there any reason not to do it?
As suggested also in some comments, here's a reason not to do it: while it provides a patterned option, it avoids dealing with the root of the problem - the design of the original class (class Foo).
In your question you write:
If a class has lots of private functions it seems undesirable to have them declared in the header file.
There's some subjectivity to this question so allow me to restate it more objectively with the following question.
Are there ways to avoid private member functions?
You pointed out one way, to use the PIMPL idiom. As also suggested in some comments, here's some more:
Refactor the original (a.k.a. client) class to instead use non-member non-friend functions or lambda expressions that manipulate your class member data through parameters - so that it doesn't need private member functions.
Split up the class into multiple smaller classes so that each of the smaller classes declares less of the original class's private member functions. Like with member data, the more private member functions a class has, the more likely - at least in my opinion - the class is violating the single responsibility principal. So this kind of effort can reduce the private member functions as well making your class design more robust.
Say we start with the following code:
//Foo.h
class Foo
{
public:
void FuncA();
void FuncB();
private:
void multiplyByTwo();
int x;
// more data...
};
//Foo.cpp
void Foo::multiplyByTwo()
{
x = x * 2;
}
void Foo::FuncA()
{
multiplyByTwo();
}
Here's an example using the first way of what this could be changed to:
//Foo.h
class Foo
{
public:
void FuncA();
void FuncB();
private:
int x;
// more data...
};
//Foo.cpp
namespace {
int multiplyByTwo(int x)
{
return x * 2;
}
}
void Foo::FuncA()
{
x = multiplyByTwo(x);
}
In addition to eliminating the declaration of multiplyByTwo as a private member function of class Foo, this change also more idiomatically expresses the intention of the multiplyByTwo function in now saying in C++ syntax what's its input and output.

What are static object of class, inside the class definition, and what are different ways for calling static member function of a class?

I found a similar code like the one shown below, and two things confuse me. The first one, is it possible to have an object of the class, inside of the definition of the class, as in the example below in code 1? I though this was not possible, but maybe the static keyword is making this possible. Is this right? what is it actually happening here?
The second one, I learned that we can access static member variables and static member functions of a class just by calling the class name and the scope resolution operator (and the member we want). Apparently, the way described in code1 is an alternative manner of doing this. So, what is the main difference (or advantage) of doing it this way? In other words, what is the difference between code 1 and code 2?
//CODE 1
namespace LOGGER {
class Logger;
}
class LOGGER::Logger {
void foo(){}
public:
static Logger logger;
};
int main()
{
LOGGER::Logger::logger.foo();
}
//CODE 2
namespace LOGGER {
class Logger;
}
class LOGGER::Logger {
public:
static void foo(){}
};
int main()
{
LOGGER::Logger::foo();
}

Member is inaccessible

class Example{
public:
friend void Clone::f(Example);
Example(){
x = 10;
}
private:
int x;
};
class Clone{
public:
void f(Example ex){
std::cout << ex.x;
}
};
When I write f as a normal function, the program compiles successful. However, when I write f as a class member, this error occurs.
Screenshot:
The error you're seeing is not a root-cause compilation error. It is an artifact of a different problem. You're friending to a member function of a class the compiler has no earthly clue even exists yet,much less exists with that specific member.
A friend declaration of a non-member function has the advantage where it also acts as a prototype declaration. Such is not the case for a member function. The compiler must know that (a) the class exists, and (b) the member exists.
Compiling your original code (I use clang++ v3.6), the following errors are actually reported:
main.cpp:6:17: Use of undeclared identifier 'Clone'
main.cpp:17:25: 'x' is a private member of 'Example'
The former is a direct cause of the latter. But doing this instead:
#include <iostream>
#include <string>
class Example;
class Clone
{
public:
void f(Example);
};
class Example
{
public:
friend void Clone::f(Example);
Example()
{
x = 10;
}
private:
int x;
};
void Clone::f(Example ex)
{
std::cout << ex.x;
};
int main()
{
Clone c;
Example e;
c.f(e);
}
Output
10
This does the following:
Forward declares Example
Declares Clone, but does not implement Clone::f (yet)
Declares Example, thereby making x known to the compiler.
Friends Clone::f to Example
Implements Clone::f
At each stage we provide what the compiler needs to continue on.
Best of luck.

private member functions & structs and helpers local to the implementation file

Consider a class with a set of methods
class myClass {
private:
int someFunc(const SomeClass&);
public:
funcA();
funcB();
funcC();
}
Inside the implementation file, I have a local struct definition and some helper functions using this in an anonymous namespace
namespace {
struct Foo { ... };
int helperFunc(const Foo&){
SomeClass c;
// do stuff with Foo and SomeClass to calculate someInteger
return someInteger;
}
Foo makeFoo(){
Foo foo;
// configure foo
return foo;
}
}
myClass::funcA(){
Foo foo = makeFoo();
return helperFunc(foo);
}
myClass::funcB(){
Foo foo = makeFoo();
return helperFunc(foo);
}
myClass::funcC(){
Foo foo = makeFoo();
return helperFunc(foo)
}
Now, I discovered that I need to change the helperFunc to use someFunc(c), a private method of myClass.
Ideally, I would like to
keep the defintion of Foo local to the anonymous namespace
keep someFunc private
keep helperFunc as a function, because it's used multiple times in the class implementation
keep makeFoo separate from helperFunc, because it's used separately in some cases
As a last resort, one could convert helperFunc to a precompiler macro, but I consider this not very elegant and still hope that there is some trick that I'm unaware of to achieve my goals.
I greatly appreciate any suggestions.
You could pass an std::function object to helperFunc. This object can be constructed from your private method using std::bind:
namespace {
...
int helperFunc(const Foo&, std::function<int(const SomeClass&)> func){
SomeClass c;
...
// Invoke passed-in function
int funcResult = func(c);
...
return someInteger;
}
...
}
myClass::funcA(){
Foo foo = makeFoo();
return helperFunc(foo, std::bind(&myClass::someFunc, this, std::placeholders::_1));
}
There's more than a single way to do it. Personally, I'd go with:
namespace detail
{
int myClassSomeFuncAccessor(const SomeClass&);
}
class myClass {
private:
int someFunc(const SomeClass&);
public:
int funcA();
int funcB();
int funcC();
private:
friend int detail::myClassSomeFuncAccessor(const SomeClass&);
};
It has pros and cons.
Pros:
Decouples the class and its accessor from the implementation classes
detail namespace accessor signifies that this is not part of the "official public" interface
Cons:
The decoupling is indeed decoupled: anyone can access the internals through the detail namespace accessor
I think now is the perfect occasion of use of C++ keyword 'friend'. Simply make your inner class friend of the encapsulator. This is the cleanest and language supported solution.
In an article about the topic by Alex Allain he explains it nicely how friend in C++ are not taboo by saying
Some people believe that the idea of having friend classes violates the principle of encapsulation because it means that one class can get at the internals of another. One way to think about this, however, is that friend is simply part of a class's overall interface that it shows the world. Just like an elevator repairman has access to a different interface than an elevator rider, some classes or functions require expanded access to the internals of another class. Moreover, using friend allows a class to present a more restrictive interface to the outside world by hiding more details than may be needed by anything but the friends of the class.

How can I test private members and methods of classes?

I am trying to do unit testing (using the Boost unit testing framework) on a C++ class called VariableImpl. Here are the details.
class Variable
{
public:
void UpdateStatistics (void) {
// compute mean based on m_val and update m_mean;
OtherClass::SendData (m_mean);
m_val.clear ();
}
virtual void RecordData (double) = 0;
protected:
std::vector<double> m_val;
private:
double m_mean;
};
class VariableImpl : public Variable
{
public:
virtual void RecordData (double d) {
// Put data in m_val
}
};
How can I check that the mean is computed correctly? Note that 1) m_mean is protected and 2) UpdateStatistics calls a method of another class and then clears the vector.
The only way I can see would be to add a getter (for instance, GetMean), but I don't like this solution at all, nor I think it is the most elegant.
How should I do?
And what should I do if I were to test a private method instead of a private variable?
Well, unit testing should test units and ideally every class is a self-contained unit – this follows directly from the single responsibility principle.
So testing private members of a class shouldn’t be necessary – the class is a black box that can be covered in a unit test as-is.
On the other hand, this isn’t always true, and sometimes with good reasons (for instance, several methods of the class could rely on a private utility function that should be tested). One very simple, very crufty but ultimately successful solution is to put the following into your unit-test file, before including the header that defines your class:
#define private public
Of course, this destroys encapsulation and is evil. But for testing, it serves the purpose.
For a protected method/variable, inherit a Test class from the class and do your testing.
For a private, introduce a friend class. It isn't the best of solutions, but it can do the work for you.
Or this hack:
#define private public
In general, I agree with what others have said on here - only the public interface should be unit tested.
Nevertheless, I've just had a case where I had to call a protected method first, to prepare for a specific test case. I first tried the #define protected public approach mentioned above; this worked with Linux/GCC, but failed with Windows and Visual Studio.
The reason was that changing protected to public also changed the mangled symbol name and thus gave me linker errors: the library provided a protected __declspec(dllexport) void Foo::bar() method, but with the #define in place, my test program expected a public __declspec(dllimport) void Foo::bar() method which gave me an unresolved symbol error.
For this reason, I switched to a friend based solution, doing the following in my class header:
// This goes in Foo.h
namespace unit_test { // Name this anything you like
struct FooTester; // Forward declaration for befriending
}
// Class to be tested
class Foo
{
...
private:
bool somePrivateMethod(int bar);
// Unit test access
friend struct ::unit_test::FooTester;
};
And in my actual test case, I did this:
#include <Foo.h>
#include <boost/test/unit_test.hpp>
namespace unit_test {
// Static wrappers for private/protected methods
struct FooTester
{
static bool somePrivateMethod(Foo& foo, int bar)
{
return foo.somePrivateMethod(bar);
}
};
}
BOOST_AUTO_TEST_SUITE(FooTest);
BOOST_AUTO_TEST_CASE(TestSomePrivateMethod)
{
// Just a silly example
Foo foo;
BOOST_CHECK_EQUAL(unit_test::FooTester::somePrivateMethod(foo, 42), true);
}
BOOST_AUTO_TEST_SUITE_END();
This works with Linux/GCC as well as Windows and Visual Studio.
A good approach to test the protected data in C++ is the assignment of a friend proxy class:
#define FRIEND_TEST(test_case_name, test_name)\
friend class test_case_name##_##test_name##_Test
class MyClass
{
private:
int MyMethod();
FRIEND_TEST(MyClassTest, MyMethod);
};
class MyClassTest : public testing::Test
{
public:
// ...
void Test1()
{
MyClass obj1;
ASSERT_TRUE(obj1.MyMethod() == 0);
}
void Test2()
{
ASSERT_TRUE(obj2.MyMethod() == 0);
}
MyClass obj2;
};
TEST_F(MyClassTest, PrivateTests)
{
Test1();
Test2();
}
See more Google Test (gtest).
Unit test VariableImpl such that if its behavior is ensured, so is Variable.
Testing internals isn't the worst thing in the world, but the goal is that they can be anything as long as the interfaces contracts are ensured. If that means creating a bunch of weird mock implementations to test Variable, then that is reasonable.
If that seems like a lot, consider that implementation inheritance doesn't create great separation of concerns. If it is hard to unit test, then that is a pretty obvious code smell for me.
While in my opinion the need of testing private members/methods of a class is a code smell, I think that is technically feasible in C++.
As an example, suppose you have a Dog class with private members/methods except for the public constructor:
#include <iostream>
#include <string>
using namespace std;
class Dog {
public:
Dog(string name) { this->name = name; };
private:
string name;
string bark() { return name + ": Woof!"; };
static string Species;
static int Legs() { return 4; };
};
string Dog::Species = "Canis familiaris";
Now for some reason you would like to test the private ones. You could use privablic to achieve that.
Include a header named privablic.h along with the desired implementation like that:
#include "privablic.h"
#include "dog.hpp"
then map some stubs according to types of any instance member
struct Dog_name { typedef string (Dog::*type); };
template class private_member<Dog_name, &Dog::name>;
...and instance method;
struct Dog_bark { typedef string (Dog::*type)(); };
template class private_method<Dog_bark, &Dog::bark>;
do the same with all static instance members
struct Dog_Species { typedef string *type; };
template class private_member<Dog_Species, &Dog::Species>;
...and static instance methods.
struct Dog_Legs { typedef int (*type)(); };
template class private_method<Dog_Legs, &Dog::Legs>;
Now you can test them all:
#include <assert.h>
int main()
{
string name = "Fido";
Dog fido = Dog(name);
string fido_name = fido.*member<Dog_name>::value;
assert (fido_name == name);
string fido_bark = (&fido->*func<Dog_bark>::ptr)();
string bark = "Fido: Woof!";
assert( fido_bark == bark);
string fido_species = *member<Dog_Species>::value;
string species = "Canis familiaris";
assert(fido_species == species);
int fido_legs = (*func<Dog_Legs>::ptr)();
int legs = 4;
assert(fido_legs == legs);
printf("all assertions passed\n");
};
Output:
$ ./main
all assertions passed
You can look at the sources of test_dog.cpp and dog.hpp.
DISCLAIMER: Thanks to insights of other clever people, I have assembled the aforementioned "library" able to access to private members and methods of a given C++ class without altering its definition or behaviour. In order to make it work it's (obviously) required to know and include the implementation of the class.
NOTE: I revised the content of this answer in order to follow directives suggested by reviewers.
I generally suggest testing the public interface of your classes, not the private/protected implementations. In this case, if it can't be observed from the outside world by a public method, then the unit test may not need to test it.
If the functionality requires a child class, either unit test the real derived class OR create your own test derived class that has an appropriate implementation.
Example from the Google testing framework:
// foo.h
#include "gtest/gtest_prod.h"
class Foo {
...
private:
FRIEND_TEST(FooTest, BarReturnsZeroOnNull);
int Bar(void* x);
};
// foo_test.cc
...
TEST(FooTest, BarReturnsZeroOnNull) {
Foo foo;
EXPECT_EQ(0, foo.Bar(NULL));
// Uses Foo's private member Bar().
}
The main idea is the use of the friend C++ keyword.
You can extend this example as follows:
// foo.h
#ifdef TEST_FOO
#include "gtest/gtest_prod.h"
#endif
class Foo {
...
private:
#ifdef TEST_FOO
FRIEND_TEST(FooTest, BarReturnsZeroOnNull);
#endif
int Bar(void* x);
};
You can define the TEST_FOO preprocessor symbol in two ways:
within the CMakeLists.txt file
option(TEST "Run test ?" ON)
if (TEST)
add_definitions(-DTEST_FOO)
endif()
as arguments to your compiler
g++ -D TEST $your_args