【发布时间】:2015-05-14 01:39:58
【问题描述】:
取如下代码,其特点是
- 特定行为依赖 ADL (
volume) - 使用 decltype 作为返回类型并依靠 SFINAE 丢弃额外的重载
namespace Nature {
struct Plant {};
double volume(Plant){ return 3.14; }
}
namespace Industrial {
struct Plant {};
double volume(Plant) { return 100; }
}
namespace SoundEffects {
// A workaround for GCC, but why?
////template<class T> void volume();
template<class aSound>
auto mix(aSound& s) -> decltype(volume(s)*0.1)
{
return volume(s)*.1;
}
struct Samples {
Nature::Plant np;
Industrial::Plant ip;
};
inline double mix(const Samples& s) {
return mix(s.np) + mix(s.ip);
}
}
int main()
{
SoundEffects::Samples s;
assert( mix(s) == 100*.1 + 3.14*.1 );
}
提供的代码(没有template<class T> void volume() 行)、VS 2012 和 clang 3.5 编译成功,运行时符合预期。但是,GCC 4.7.2 说:
template-function-overload.cpp: In substitution of 'template<class aSound> decltype ((volume(s) * 1.0000000000000001e-1)) SoundEffects::mix(aSound&) [with aSound = SoundEffects::Samples]':
template-function-overload.cpp:46:4: required from here
template-function-overload.cpp:23:9: error: 'volume' was not declared in this scope
template-function-overload.cpp:23:9: note: suggested alternatives:
template-function-overload.cpp:9:11: note: 'Nature::volume'
template-function-overload.cpp:14:11: note: 'Industrial::volume'
使用额外的template volume 行,所有三个都可以编译并运行良好。
因此,这里显然存在编译器缺陷。我的问题是,哪个编译器是有缺陷的?违反了哪个 C++ 标准?
【问题讨论】:
标签: c++ templates c++11 argument-dependent-lookup