Wulgryn
Wulgryn

Reputation: 41

C++ non-generic class in template

I would like to know how to make a template with an own class:

#include <iostream>
using namespace std;

template<C cc> void A()
{
    cout << cc.l << endl;
}

int main()
{
    C cc;
    A<cc>();
}

class C
{
public:
    int l = 10;
};

But it doesn't work, so how to use that class, like a non-generic class parameter, like here:

#include <iostream>
using namespace std;

template<int i> void A()
{
    cout << i << endl;
}

int main()
{
    A<100>();
}

Upvotes: 1

Views: 194

Answers (1)

user12002570
user12002570

Reputation: 1

You can do it as shown below with C++20(&onwards):

//moved definition of C before defining function template `A`
struct C 
{
    int l = 10;
};
template<C cc> void A()
{
    cout << cc.l << endl;
}

int main()
{
//--vvvvvvvvv--------->constexpr added here
    constexpr C cc;
    A<cc>();
}

Working demo


Two changes have been made:

  1. As template arguments must be compile time constant, constexpr is used.

  2. The definition of C is moved before the definition of function template.

Upvotes: 8

Related Questions