我有一个 namespace 中的操作的定义,我想在另一个 namespace 中使用它,我该怎么做:
例如,假设我有以下操作定义:
namespace op
{
inline cv::Matx21f operator/(const cv::Matx21f &v, float a)
{
return cv::Matx21f(v(0) / a, v(1) / a);
}
}
我在另一个命名空间中的代码为:
namespace code
{
void my function()
{
cv::Matx21f data=getData();
cv::Matx21f result=data/10;
}
}
我遇到错误
cv::Matx21f result=data/10;
由于/未定义。
我知道我可以使用:
use namespace op;
但我不想这样做。
我可以通过与函数名称解析相同的任何方式来解决该操作(op::/无效)
最佳答案
请考虑以下代码:
namespace WhateverLibraryNs
{
inline namespace operations
{
inline cv::Matx21f operator/(const cv::Matx21f &v, float a)
{
return cv::Matx21f(v(0) / a, v(1) / a);
}
}
}
WhateverLibraryNs
中的客户端代码将无缝使用运算符(因为它是一个内联 namespace )。WhateverLibraryNs
之外的客户端代码将具有四个选项:首先,完全符合条件的运算符(operator):
auto result = WhateverLibraryNs::operations::operator/(v, a);
其次,仅导入操作 namespace (有关类似的解决方案,请参见std::string_literals namespace ):
using namespace WhateverLibraryNs::operations;
auto result = v / a;
第三,别名内部命名空间:
namespace ops = WhateverLibraryNs::operations;
auto result = ops::operator/(v, a);
第四,仅导入运算符:
using WhateverLibraryNs::operations::operator/;
auto result = v / a;
关于c++ - 如何使用C++中另一个命名空间中定义的操作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30075489/