2

I was asked a question

Which class functions can be templated in C++? (constructor, destructor, const, static)

Did I understand correctly that all class methods (except destructor) can be templated?

Constructor / destructor

class A {
public:
    template<class T>
    A(T t) {
        cout << t << endl; 
    }

    /*
    template<class U>
    ~A() {  // error: destructor cannot be declared as a template
        cout << "Destructor\n";
    }*/

};


int main() {
    A a(5);
}

Static function -- yes, it can be template

class A {
public:
    template< typename T>
    static double foo( vector<T> arr );

};

template< typename T>
double A::foo( vector<T> arr ){ cout << arr[0] << endl; }

int main() {
    A a;
    A::foo<int>({1, 2, 3});
}

non-constant / constant method -- yes

class A {
public:
    template< typename T>
    double foo( vector<T> arr ) const {
        cout << arr[0] << endl;
    }

};


int main() {
    A a;
    a.foo<int>({1, 2, 3});
}
mascai
  • 1,373
  • 1
  • 9
  • 30
  • 1
    You can only have a template constructor when implicit argument deduction can be used, not in all cases: https://stackoverflow.com/questions/3960849/c-template-constructor – VLL Mar 29 '23 at 10:16
  • 1
    A class can only have one destructor, and a template is the means of automatically generating a family of functions. So having a templated destructor is not allowed (essentially because it would be pointless and potentially misleading to have one). A class can have as many (static or non-static) other member functions as judged appropriate to its design - so they can (if appropriate) be templated. – Peter Mar 29 '23 at 10:22
  • 1
    I also tried to define a template cast operator. It works. But it seems you can not define a template cast to another type (like this: `template operator double() const { return (double)T(); }`) – Caduchon Mar 29 '23 at 14:01
  • 1
    @Caduchon Curiously, you [can in fact](https://godbolt.org/z/f8GezvafY) define a templated conversion operator like this - but there doesn't appear to be any syntax to actually call it. So it's mostly of academic interest. – Igor Tandetnik Apr 01 '23 at 15:06

0 Answers0