【问题标题】:Error while compiling code having | operator overloaded under template definition ,with VS2017 Update8.2编译代码时出错 |运算符在模板定义下重载,VS2017 Update8.2
【发布时间】:2018-10-29 08:38:52
【问题描述】:

我的问题是,在使用 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>' 的参考

我正在共享代码 sn-p,它会产生相同的编译错误。请有人帮我解决这个问题。

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

我的代码:
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) {
}
}

【问题讨论】:

    标签: c++


    【解决方案1】:

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

    您的示例中的错误是因为 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;
    }
    
    }
    

    另外:也许您可以通过https://en.cppreference.com/w/cpp/utility/rel_ops/operator_cmp 了解 STL 是如何做到这一点的

    【讨论】:

    • 感谢您的回答
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-26
    • 1970-01-01
    • 2017-04-05
    • 2018-12-26
    • 2018-09-17
    相关资源
    最近更新 更多