c++namespacesvector-class-library

How to use VCL as a separate namespace?


My goal is to separate all vectorclass-library typenames to a separate namespace, so that vcl::Vec4i will compile, but Vec4i won't. I tried to use example from manual, however it's not working.

Failed attempt following the manual:

#include <iostream>
#include "vcl/vectorclass.h"
#define VCL_NAMESPACE vcl
using namespace vcl; //error
int main() {
 vcl::Vec4i vec; //error
 Vec4i vec; //still compiles
 return 0;
}

Failure message:

root@vlad:/avx_vcl clang++ -std=c++17 -mavx -o test main.cpp 
main.cpp:4:17: error: expected namespace name
using namespace vcl;
                ^
main.cpp:6:2: error: use of undeclared identifier 'vcl'
        vcl::Vec4i vec;
        ^
2 errors generated.

Desired result:

#define VCL_NAMESPACE vcl
int main() {
 vcl::Vec4i vec; //compiles
 Vec4i vec; //won't compile
 return 0;
}

What should I change?


Solution

  • As noted in chapter 2.7 Using a namespace, you need to define VCL_NAMESPACE before including any vcl headers, directly or indirectly, so change the order to:

    #define VCL_NAMESPACE vcl
    #include "vcl/vectorclass.h"   // this line after the #define
    using namespace vcl;           // ...and now this will work
    

    If we look inside vectori128.h which defines Vec4i we see that all of the definitions in the file are surrounded by an #ifdef VCL_NAMESPACE pair:

    #ifdef VCL_NAMESPACE
    namespace VCL_NAMESPACE {
    #endif
    
    // all the definitions, including Vec4i
    
    #ifdef VCL_NAMESPACE
    }
    #endif
    

    So, what happens is that if you don't define VCL_NAMESPACE before including any of those headers, it will not put them in the namespace you've selected.

    Note - You need to put this #define VCL_NAMESPACE vcl first in all your files that include any vcl header, directly or indirectly. It may be easiest to give the compiler the instruction to just define it always. g++ example:

    g++ -DVCL_NAMESPACE=vcl ...