decltype 的另一个问题
template<class IntT, IntT low = IntT(), IntT high = IntT()>
struct X
{
static_assert(std::is_same<decltype(low),decltype(high)>::value,"Different types not allowed");//this should give error if types are different
decltype(low) a;
decltype(high) b;
X():a(decltype(a)()),b(decltype(b)())//WHY THIS DOES NOT COMPILE?
{
cout << typeid(a).name() << '\n';
cout << typeid(b).name() << '\n';
}
};
int _tmain(int argc, _TCHAR* argv[])
{
X<char,1,'a'> x;//this according to static_assert shouldn't compile but it does
return 0;
}
使用VS2010。
请参阅上面代码中的 3 条注释。
template<class IntT, IntT low = IntT(), IntT high = IntT()>
struct X
{
static_assert(std::is_same<decltype(low),decltype(high)>::value,"Different types not allowed");//this should give error if types are different
decltype(low) a;
decltype(high) b;
X():a(decltype(a)()),b(decltype(b)())//WHY THIS DOES NOT COMPILE?
{
cout << typeid(a).name() << '\n';
cout << typeid(b).name() << '\n';
}
};
int _tmain(int argc, _TCHAR* argv[])
{
X<char,1,'a'> x;//this according to static_assert shouldn't compile but it does
return 0;
}
Using VS2010.
Please see 3 comments in code above.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
首先值得注意的是,VS2010 已经过时了,并且在发布之日就被破坏了。 decltype 关键字尤其有问题,并且仅适用于最基本的用途。事实上,它把很多基本的事情都搞错了。
接下来是代码......
但他们永远不会。
这里不需要 decltype。类型为 IntT。
因为 VS2010 已损坏,并且通常不允许您使用 decltype 表达式,就好像它是类型一样。事先 typedef 可能会更好。
幸运的是,您不需要这个,因为您可以只使用默认构造函数而不是副本。
否。 static_assert 检查类型是否相同。它们都是 值 1 和“a”的
char
。您似乎正在尝试创建一个模板,以便第二个和第三个参数的类型基于您传递给它的值的解析类型。这是不可能的。
First thing of note, VS2010 is outdated and was broken the day it was released. The decltype keyword was especially problematic and only works for the most basic of uses. In fact it gets a lot of basic things quite wrong.
Next the code...
But they never will be.
You don't need decltype here. The type is IntT.
Because VS2010 is broken and quite usually won't allow you to use a decltype expression as if it where a type. A typedef before hand might do better.
Luckily you don't need this since you can just use the default constructor rather than the copy.
No. The static_assert checks if the types are the same. They are both
char
with values 1 and 'a'.What you appear to be attempting is to create a template such that the type of the second and third parameters are based on whatever resolved type of the value you pass into it. This can't be done.
static_assert 确实可以编译,因为模板参数 low 和 high 的 decltype 是 char。查看您的模板定义和实例化。 IntT <-- char
要默认初始化您的成员,您可以这样写:
The static_assert does compile because the decltype of the template parameters low and high is char. Look at your template definition and the instantiation. IntT <-- char
To default initialize your members you can write this:
GCC 编译得很好。请参阅: http://www.ideone.com/DG7rt
看起来是 MSVC++10 编译器错误!
GCC compiles it fine. See this : http://www.ideone.com/DG7rt
Looks like it's MSVC++10 compiler bug!