Feature specialized with pattern

I need to specialize my function with a template class and have a problem with the "illegal use of explicit template arguments".

template <typename T>
class MyClass { /* ... */ }; // it can be any template class, eg std::vector

template <typename T>
void foo() { /* ... */ } // my template function which need a specialization

template<> 
void foo<int>() /* sth special for integers - it works */ }

template<template T> 
void foo<MyClass<T> >() /* sth special for template class with any parameter - it doesnt work :( */ }

Of course, I can print several specializations for all MyClass'ov that I need, but maybe they can be replaced with one?

+5
source share
4 answers

Template specialization is not as flexible as specialization struct: only full specialization is allowed. If you want to do partial specialization, you need to wrap your function fooinside struct:

template <typename T> class MyClass { };

template <typename T> struct Foo;

template <typename T> struct Foo { void foo() {}};

template<> struct Foo<int> { void foo() { } };

template<typename T> struct Foo< MyClass<T> > { void foo() {} };

And then instead of calling

foo<MyClass<...>>()

you call

Foo< MyClass<...> >::foo()
+5
source

. .

:

  1. .
  2. .
template <typename T>
struct foo_impl {
};
template <typename T>
void foo() {
    foo_impl<T>();
}

// And now specialize foo_impl as you want:

template<>
struct foo_impl<int> {
    foo_impl(){/* sth special for integers - it works */}
};
template<typename T>
struct foo_impl<myclass<T>> {
   foo_impl() {/* ... */}
};

, - - , operator() - ctor.

+2

template<typename T> class MyClass;

class base {
private:
    template<typename T> friend class MyClass;
    base(); // Can't build a base object directly
};

template <typename T>
class MyClass : public base { 
public:
}; // it can be any template class, eg std::vector

template <typename T>
void foo() {
} // my template function which need a specialization

template<> 
void foo<int>() { /* sth special for integers - it works */ }

template<>
void foo<base>() { /* sth special for template class with any parameter - it doesnt work :( */ }

, . , hivert.

+1

, :

template <typename T>
class MyClass { /* ... */ }; // it can be any template class, eg std::vector

template<typename T>
struct FooWrapper
{
    static void foo()
    {
       // default implementation
    }
};

template<typename T>
struct FooWrapper<MyClass<T>>
{
    static void foo()
    {
        // MyClass<T> implementation
    }
};

template<typename T>
void foo()
{
    FooWrapper<T>::foo();
}
+1

Source: https://habr.com/ru/post/1539809/


All Articles