繁体   English   中英

编译具有|的代码时出错 VS2017 Update8.2在模板定义下重载了运算符

[英]Error while compiling code having | operator overloaded under template definition ,with VS2017 Update8.2

我的问题是,在使用Visual Studio 2017 Update 8.2编译C ++源代码时,我遇到编译错误并显示以下消息:

sstream(270):错误C2131:表达式未求值为常数

sstream(270):注意:失败是由于调用未定义函数或未声明“ constexpr”引起的

sstream(270):注意:请参阅“ operator |”的用法

sstream(249):注意:编译类模板成员函数'std :: fpos <_Mbstatet> std :: basic_stringbuf,std :: allocator> :: seekoff(__ int64,std :: ios_base :: seekdir,std :: ios_base: :用于openmode)”

sstream(730):注意:请参见对正在编译的类模板实例化'std :: basic_stringbuf,std :: allocator>'的引用

test.cpp(3):注意:请参见对正在编译的类模板实例化'std :: basic_stringstream,std :: allocator>'的引用

我正在共享可能产生相同编译错误的代码段。 请有人帮助我。

给出的答案很好,解决了几个问题。 但是我面临另一个问题。 我将重载的模板放在命名空间中,但将其放在头文件中,因为现有代码在头文件中具有重载的模板。 我再次面临着同样的问题。 我现在正在更新代码

我的代码:
cpp文件test.cpp

#include "test.hpp"
#include <sstream>
namespace testing 
{
struct Message {
    std::stringstream ss_;
};
} 

using namespace ABC;
int main() {
return 0;
}

头文件test.hpp

namespace ABC 
{

template <typename T>

bool operator|(T v1, T v2) {
}
}

为重载运算符定义全局函数模板确实很危险,因为它将影响与使用已重载运算符的作用域相同范围内的现有代码。

您的示例中的错误是因为MSVC尝试编译

constexpr auto _Both = ios_base::in | ios_base::out;

与您的operator | 和(不幸的),您的重载函数不是constexpr函数。

解决方案很简单:将重载的模板放入命名空间中:

namespace ext_ops {

// operator to combine two parameter attributes v1 and v2, e.g.,
template <typename T>
bool operator|(T v1, T v2) {
    return false;
}

}

撇开:也许您可以通过以下网址查看STL如何做到这一点: https//en.cppreference.com/w/cpp/utility/rel_ops/operator_cmp

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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