Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it bad to use #include in the middle of code?

Tags:

c++

I keep reading that it's bad to do so, but I don't feel those answers fully answer my specific question.

It seems like it could be really useful in some cases. I want to do something like the following:

class Example {
    private:
        int val;
    public:
        void my_function() {
#if defined (__AVX2__)
    #include <function_internal_code_using_avx2.h>
#else
    #include <function_internal_code_without_avx2.h>
#endif
        }
};

If using #include in the middle of code is bad in this example, what would be a good practice approach for to achieve what I'm trying to do? That is, I'm trying to differentiate a member function implementation in cases where avx2 is and isn't available to be compiled.

like image 911
thc Avatar asked Dec 23 '22 00:12

thc


1 Answers

No it is not intrinsically bad. #include was meant to allow include anywhere. It's just that it's uncommon to use it like this, and this goes against the principle of least astonishment.

The good practices that were developed around includes are all based on the assumption of an inclusion at the start of a compilation unit and in principle outside any namespace.

This is certainly why the C++ core guidelines recommend not to do it, being understood that they have normal reusable headers in mind:

SF.4: Include .h files before other declarations in a file

Reason

Minimize context dependencies and increase readability.

Additional remarks: How to solve your underlying problem

Not sure about the full context. But first of all, I wouldn't put the function body in the class definition. This would better encapsulate the implementation specific details for the class consumers, which should not need to know.

Then you could use conditional compilation in the body, or much better opt for some policy based design, using templates to configure the classes to be used at compile time.

like image 191
Christophe Avatar answered Jan 02 '23 11:01

Christophe