Ensure derived class implements static method

后端 未结 1 1747
忘了有多久
忘了有多久 2020-12-18 01:58

I want to ensure, that a derived class implements a specific static method. I think doing so should be possible using static_assert, std::is_same, decltype, CRTP and maybe m

1条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-18 02:27

    This is a common problem when using CRTP: Base is instantiated at the point where it is encountered in Derived's list of bases, at which time Derived is not yet a complete type since the rest of its declaration hasn't been parsed yet. There are various workarounds. For static_assert, you need to delay instantiation of the assertion until Derived is complete. One way to do so is to put the assertion in a member function of Base that you know must be instantiated - the destructor is always a good choice (Live at Coliru):

    template 
    class Base 
    {
    public:
        ~Base() {
            static_assert(std::is_same::value, "ERROR STRING");
        }
    };
    
    class Derived : public Base
    {
    public:
        static int foo(int) { return 42; };
    };
    

    Addressing question #2: C::* is the syntax for "pointer to member of class C." So int(*)(int) is "pointer to function taking a single int parameter and returning int", and int(C::*)(int) is analogously "pointer to member function of C taking a single int parameter and returning int." The monstrosity

    typename C::const_iterator(C::*)() const
    

    would translate to "pointer to constant member function of C taking no parameters and returning C::const_iterator" where of course the typename is necessary to indicate that the dependent name C::const_iterator is a type.

    0 讨论(0)
提交回复
热议问题