简体   繁体   English

具有模板化和非模板化形式的C ++类

[英]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. 如果您希望默认类型的成员函数具有不同的行为,请使用特殊化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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