简体   繁体   English

没有模板参数的C ++模板?

[英]C++ template with no template parameters?

I hate the boilerplate and Don't Repeat Yourself violations inherent in traditional class declarations in C++. 我讨厌样板,并且不要重复C ++中传统类声明中固有的违规行为。

Is it possible to create a template with no template parameters, purely to enable the class to be defined in a header file without violating the One Definition Rule, in C++11? 是否可以创建没有模板参数的模板,而仅仅是为了使类能够在头文件中定义而又不违反C ++ 11中的“一个定义规则”?

There's no need for templates whatsoever. 完全不需要模板。

If you want to write a header-only class, all you have to do is mark inline the functions that will be defined external to the class declaration: 如果要编写仅标头的类,则要做的就是将要在类声明外部定义的函数标记为inline

#pragma once

struct some_class {
    void implicitly_inline() { ... }

    inline void explicitly_inline();
};

void some_class::explicitly_inline() { ... }

The occasional extra inline keyword is hardly such a burden as to change the entire definition of your class. 偶尔使用额外的inline关键字几乎不会改变整个类的定义。

Is it possible to create a template with no template parameters 是否可以创建没有模板参数的模板

No. And you don't need for such workaround because... 不,您不需要这种解决方法,因为...

to enable the class to be defined in a header file without violating the One Definition Rule 使类可以在头文件中定义而不会违反“一个定义”规则

You can define a class in a header file without violating the One Definition Rule. 您可以在头文件中定义一个类,而不会违反“一个定义规则”。

You can even define the member functions of a class in a header - which I think is the point of this question. 您甚至可以在标头中定义类的成员函数-我认为这是此问题的重点。 Simply declare them all inline . 只需将它们全部内联声明即可。 If you define the member functions within the class definition, then they're implicitly inline. 如果在类定义中定义成员函数,则它们是隐式内联的。

There may be more than one definition of an inline function in the program as long as each definition appears in a different translation unit. 程序中的内联函数定义可能不止一个,只要每个定义出现在不同的翻译单元中即可。 For example, an inline function may be defined in a header file that is #include'd in multiple source files. 例如,可以在包含在多个源文件中的头文件中定义内联函数。

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

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