Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I can use private methods from template functions

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.

  1. Compiler doesn't report error.

    template <class T>
    void f()
    {
      MyClass<int> a;
      a.PrivateFunction();
    }
    
  2. Compiler reports error.

    void f()
    {
      MyClass<int> a;
      a.PrivateFunction();
    }
    
like image 855
Ashot Khachatryan Avatar asked Dec 11 '22 03:12

Ashot Khachatryan


1 Answers

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)

like image 168
Piotr Skotnicki Avatar answered Dec 24 '22 20:12

Piotr Skotnicki