简体   繁体   中英

C++ Class with templated and non-templated form

I am curious if it is possible to have a class with both a templated and non-templated form. Something like:

SomeClass foo;
SomeClass<int> bar;

foo.do_something();
bar.do_something(5);

I am fine defining everything more than once, but I don't know if it's possible to use the same class name.

Short answer: no, it's not allowed. The exact error message your compiler gives you will vary, but you should get an error message.

You can, however, provide default parameters for a template, so you can instantiate it with only <> , like:

template <class T=int>
class X {};

int main(){ 
    X<long> a;
    X<>     b; // used default, so equivalent to "X<int> b;"
}

You can get something close, by using default template parameters:

template <class T = char>
class SomeClass{};

SomeClass<> foo;     // char type
SomeClass<int> bar;  // int type

Use specialization if you want different behaviour for the default type's member functions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM