【发布时间】:2014-09-02 05:52:47
【问题描述】:
这是我从几个头文件拼接在一起的可编译示例。代码没有意义,因为我删除了所有不相关的部分,但要点是我正在实现 Scott Meyers 的数据代理技术(提到here),尽管它已经演变成更多的包装器而不是临时代理。不过,这些都不重要——我的问题似乎纯粹是关于编译器行为的差异。
#include <iostream>
#include <vector>
template<typename T>
class Proxy
{
public:
enum class State
{
NEVER_SET = 0,
SET,
UNSET
};
operator const T& () const
{
if ( _state != State::SET )
{
std::cout << "EXCEPTION" << std::endl;
// TODO throw exception
}
return _data;
}
Proxy<T>& operator=(const T& val)
{
_data = val;
_state = State::SET;
return (*this);
}
Proxy<T>& operator+=(const T& val)
{
_data = (*this) + val;
_state = State::SET;
return (*this);
}
private:
T _data;
State _state = State::NEVER_SET;
};
class Tape
{
};
template<typename T>
class tape : public Tape
{
public:
const Proxy<T>& operator[](int idx) const
{
return operator[](idx);
}
Proxy<T>& operator[](int idx)
{
if ( idx >= data.size() )
{
data.resize(idx + 1);
}
return data[idx];
}
private:
std::vector< Proxy<T> > data;
};
class CRIXUS
{
public:
virtual void Go() final {};
protected:
virtual void Pre() {};
virtual void Post() {};
virtual void Step() = 0;
};
class CRIXUS_MA : public CRIXUS
{
public:
int window = 30;
tape<double> input;
tape<double> output;
protected:
virtual void Step()
{
double sum = 0;
for ( int j = 0; j < window; j++ )
{
sum += input[-j];
}
output[0] = sum / window;
}
};
int main()
{
}
它可以在 Ideone 以及 Jetbrain 的 CLion 上正常编译(工具链:MinGW 3.20,CMake 2.8.12.2):
但是它不会在 VS Express 2013 上编译:
运行 CLion 的完整代码(包括读取 .csv 数字文件并输出移动平均值),我可以验证输出是否正确。只是VS不会编译代码。
据我所知,演员表操作员
operator const T& () const
{
if ( _state != State::SET )
{
std::cout << "EXCEPTION" << std::endl;
// TODO throw exception
}
return _data;
}
应该将Proxy<T> 转换为T,即 Proxy<double> 转换为double。而当我强行投出违规的台词时,
sum += (double)input[-j];
它工作正常。有什么想法吗?
【问题讨论】:
-
第86行是哪一行?
-
啊,对不起。这是
sum += input[-j];。在那里,input[-j]应该返回一个Proxy<double>,但由于sum是double,我希望会发生转换。 -
@AndrewCheong:找到这个:stackoverflow.com/questions/4622330/…
-
显然 MSVC 拒绝在此代码中实例化
Proxy<double>。在CRIXUS_MA的定义之前添加Proxy<double> p;会强制实例化,并导致代码编译。 -
@EdS。实际上,这种情况下的重载解析将使用内置运算符并执行从
Proxy<double>到double的转换。
标签: c++ compiler-errors visual-studio-2013 mingw visual-studio-express