Home > Enterprise >  How to pass a template class and a normal class to a template parameter?
How to pass a template class and a normal class to a template parameter?

Time:01-25

template <typename T>
class myTemplateClass
{
public:
    myTemplateClass()
    {
        // do something
    }

    myTemplateClass(T t)
        : val{t}
    {
        // do something
    }
    T val;
};

class mySimpleClass
{
public:
    mySimpleClass()
    {
        // do something
    }
};

template <template<typename> class TT, typename T = void>
auto create()
{
    if constexpr (std::is_same_v<TT<T>, myTemplateClass<T>>)
    {
        // do something
        // and return
        return myTemplateClass<T>();
    }
    else
    {
        //constexpr (std::is_same_v<TT, mySimpleClass>)
        // do something
        // and return
        return  mySimpleClass{};
    }
};

int main()
{
    {
        auto result = create<myTemplateClass<int>>();
    }
    {
        auto result = create<mySimpleClass>();
    }

    return 0;
}

I tried to implement one create() function which return one of a template class and a normal class based on template parameter, but it has an error.

How can I implement create() to support this situation?

mostly, it is used as like

create<int>();
create<double>();

but if I want to mix as like create<myTemplateClass>() and create in one create function based one template function, is there any way?

CodePudding user response:

Mistake 1

First things first, the signature of main in your example is not correct. Ideally it should be int main()(instead of void main(char**, int).


Mistake 2

Moreover, myTemplateClass<int> is a class-type not a class-template.

One way to solve this would be:

template <typename Type>
auto create()
{
    return Type{};
};

CodePudding user response:

template<typename> class TT

TT is a template.

std::is_same_v<TT, mySimpleClass>

Both parameters to std::is_same_v are types, and not templates. The first parameter specified, TT, is a template instead of a type. This is the reason for your compilation error.

It is unclear what was the intent here, so it's not possible to suggest, with reasonable certainty, what should this be changed to.

  • Related