Partial Specialization and Static Member

I have the following:

template<typename T, bool is_derived = false>
struct A
{ 
    T v_;

    static const char* getMehStatic();
    virtual const char* getMeh() const { return getMehStatic(); }
};

template<typename T>
struct A<std::vector<T>> : public A<std::vector<T>, true>
{
    static const char* getMehStatic();
};

template<typename T>
const char* A<std::vector<T>>::getMehStatic() { return "vector"; }

int main()
{
    A<std::vector<int>> a;

    std::cout << a.getMeh();
}

When I compile this, the linker complains that it cannot find getMehStatic();, because it is looking for a type of a generic type. In other words, it seems that I missed my attempt to provide a partially specialized implementation A<std::vector<T>>.

I get my custom class from the generic version, using the default option to choose the right one, otherwise the custom class will be output by itself.

- getMehStatic() enable_if<>, , ( , , , , ). , -, , ?

+4
2

, -, , ?

CRTP, -

template<typename T, typename Derived = void>
struct A
{ 
    T v_;

    static const char* getMehStatic();

    virtual const char* getMeh() const {
      if constexpr( std::is_same_v<Derived,void> )
        return getMehStatic();
      else
        return Derived::getMehStatic();
    }
};

template<typename T>
struct A<std::vector<T>> : public A<std::vector<T>, A<std::vector<T>> >
{
    static const char* getMehStatic();
};

template<typename T, typename Derived>
const char* A<T,Derived>::getMehStatic() { return "generic"; }

template<typename T>
const char* A<std::vector<T>>::getMehStatic() { return "vector"; }
+1

A<std::vector<T>, true>::getMehStatic(). , . :

template<typename T, bool is_derived>
const char* A<T, is_derived>::getMehStatic() { return "generic"; }

A<std::vector<T>> getMeh(), .

CRTP :

template<typename T, typename Derived>
struct A
{ 
    T v_;

    const char* getMeh() const { return Derived::getMehStatic(); }
};

struct B : A<std::vector<int>, B>
{
    static const char* getMehStatic() { return "vector"; }
};

+2

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


All Articles