Andrew Wagner
Andrew Wagner

Reputation: 24547

C++ template with no template parameters?

I hate the boilerplate and Don't Repeat Yourself violations inherent in traditional class declarations in 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?

Upvotes: 1

Views: 369

Answers (2)

eerorika
eerorika

Reputation: 238331

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.

Upvotes: 2

Barry
Barry

Reputation: 302862

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:

#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.

Upvotes: 2

Related Questions