I have template class MyClass
template <class T>
class MyClass
{
public:
MyClass() { }
private:
void PrivateFunction() {
std::cout << "Message From Private Function" << std::endl;
}
};
Now when I am trying to use PrivateFunction() inside another function compiler reports error, but when I am trying the same inside template function compiler doesn't show any error.
Compiler doesn't report error.
template <class T>
void f()
{
MyClass<int> a;
a.PrivateFunction();
}
Compiler reports error.
void f()
{
MyClass<int> a;
a.PrivateFunction();
}
Why I can use private methods from template functions?
You can't. §14.6 [temp.res]/p4:
If no valid specialization can be generated for a template, and that template is not instantiated, the template is ill-formed, no diagnostic required.
I am interested why I cant see error before calling the function
A compiler may defer the analysis until the function template is instantiated. Still, this is an implementation-defined behavior, and your code remains ill-formed (the continuation of §14.6/p4):
[ Note: If a template is instantiated, errors will be diagnosed according to the other rules in this Standard. Exactly when these errors are diagnosed is a quality of implementation issue. — end note ]
GCC demo (issues an error only on instantiation)
Clang demo (issues an error without instantiation)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With