Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

forward declaration at class template specialisation

Tags:

c++

templates

Is the following forward declaration, at the class template specialisation stage, legal C++ code?

template<typename>
struct Basic
{};

template<>
struct Basic<struct Foo> //<-- Fwd declaration?
{};

struct Foo
{
    Basic<Foo> m_a;
};

int main()
{
    Foo test;
}

It does compile, but I'm not sure if it's legal

like image 741
Constantinos Glynos Avatar asked Oct 17 '25 14:10

Constantinos Glynos


2 Answers

template<>
struct Basic<struct Foo>
{};

is legal.

From C++11 Standard:

A class declaration introduces the class name into the scope where it is declared and hides any class, variable, function, or other declaration of that name in an enclosing scope.

like image 195
R Sahu Avatar answered Oct 20 '25 03:10

R Sahu


Yes, it is legal C++ and it does forward declare struct Foo.

You can also do this in function declarations:

void fun(struct foo);

struct foo {};

void fun(struct foo) {}

or with pointers.

struct foo* pointer;
struct foo {};

Basically anywhere where a complete type is not required. (Works with class as well.)

like image 23
DeiDei Avatar answered Oct 20 '25 04:10

DeiDei



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!