简体   繁体   中英

How to define a global struct which uses namespace so that files which use the struct do not use this namespace? c++

I have a common_module.h file which should store structures and functions used by most of .cpp files.

I want it to have an RColor struct.

RColor uses a lot of functions and variables from namespace cv. The project is made in a way that .cpp files generally do not use cv namespace (All work with it is mostly done by structures like RColor )

I don't want to always write cv::something in definition of RColor . So i tried to create an RColor prototype in common_module.h and put it definition to Rcolor.cpp :

//common_module.h
//...
struct RColor;

#include "stdafx.h"
#include<opencv2/opencv.hpp>
using namespace cv;
struct RColor
{
    ...
};

//Project0.cpp (main file)
#include "stdafx.h"
#include<stdio.h>
#include<iostream>
#include<stdlib.h>
#include<windows.h>
RColor col;

I get error:

1>error C2079: 'col' uses undefined struct 'RColor'

You're getting the error because code using RColor needs to see its definition, not just its declaration. You'll have to move the definition to the header.

As to how to deal with the namespace cv , you write:

I don't want to always write cv::something in definition of RColor .

The correct response to this is "don't be lazy, write it." Explicit qualification is good, that's what namespaces are for. At least in the class definition itself, you have no way around it (*) - you want to prevent the identifiers from cv from polluting the global namespace. Note that it also makes the code more self-documenting: cv::transform tells a reader way more about the type or function than just transform does (is the latter cv::transform or std::transform or ...?)

If you really want and need to save on typing cv:: inside member functions of RColor , you can put using namespace cv; inside the member function definitions. But I wouldn't do even that.


(*) There is actually a way to achieve what you want, but it's quite hacky (and would never pass code review with me). But out of a sense of completeness, here goes:

// common_module.h

namespace NobodyTryToUseThisName
{
  using namespace cv;

  struct RColor
  {
    // ... definition here
  };
}

using NobodyTryToUseThisName::RColor;

But as I say, I do not recommend doing this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM