Home > Mobile >  C non-generic class in template
C non-generic class in template

Time:07-13

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>();
}

CodePudding user response:

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.

  • Related