admin管理员组文章数量:1287990
The following template code is buggy as std::array has no operator() :
template <typename T> void k(T x)
{
std::array<T, 3> a { x, x, x };
std::cout << a(1) << "\n";
}
int main()
{
// k<int>(5);
return 0;
}
but GCC and CLANG won't tell it, until the template is instantiated (uncommenting the first line of main()).
Is it an expected behavior ? It does not look like a SFINAE.
Another case of not using the template is defining a base class template, and overloading one buggy method in a instantiated and derived class. The overloading hides the buggy templated one and I have no GCC nor CLANG error, despite the code being not legal.
The following template code is buggy as std::array has no operator() :
template <typename T> void k(T x)
{
std::array<T, 3> a { x, x, x };
std::cout << a(1) << "\n";
}
int main()
{
// k<int>(5);
return 0;
}
but GCC and CLANG won't tell it, until the template is instantiated (uncommenting the first line of main()).
Is it an expected behavior ? It does not look like a SFINAE.
Another case of not using the template is defining a base class template, and overloading one buggy method in a instantiated and derived class. The overloading hides the buggy templated one and I have no GCC nor CLANG error, despite the code being not legal.
Share Improve this question asked Feb 22 at 15:44 Adhémar PatamobAdhémar Patamob 851 silver badge6 bronze badges 10 | Show 5 more comments2 Answers
Reset to default 9With template code you have code that depends on the template parameters, and code that no matter what template parameters are used, that does not depend on the template parameter.
For the dependent code, the code can only be checked so much without knowing the template parameters. There could be a specialization of std::array<T, 3>
which has an operator(integer_type)
defined, so the compiler will ignore that "wrong code" until it knows what the template parameters are
This is why you do not get an error until you use the template. The code inside is considered valid enough because the non-dependent code is valid and it's only the dependent code that has the issue.
This is because you could make k
valid by specializing std::array
:
struct S {};
namespace std {
template <size_t N>
array<S> {
array(...) {}
int operator(size_t i) const { return i; }
};
}
k(S{}); // prints 1
本文标签: when the C compiler shall check for template correctnessStack Overflow
版权声明:本文标题:when the C++ compiler shall check for template correctness? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741336057a2373047.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
a(1)
should not be correct for any compiler. Do you meana[1]
or.at(1)
? – Pepijn Kramer Commented Feb 22 at 15:48