如何通过显式实例防止递归模板实例

时间:2018-10-18 16:55:14

标签: c++ templates boost

我在弄清楚如何防止对模板替换进行递归尝试并显式强制子类模板实例化时遇到麻烦

以下代码:

#include <boost/ptr_container/ptr_vector.hpp>

template <typename TemplateParameter>
struct ParentClass
{
    struct SubClass
    {
        boost::ptr_vector<SubClass> nodes;
    }; // this by itself works fine

    // but with combination with this
    void someMethod(boost::ptr_vector<SubClass>& otherNodes){} 
};

int main (int argc, char** argv)
{
    ParentClass<int> p;
    return 0;
}

使用boost 1.68和gcc 7.3.1构建的程序会出现以下错误:

test.cpp: In instantiation of ‘struct ParentClass<int>::SubClass’:
/usr/include/boost/ptr_container/nullable.hpp:55:13:   recursively required by substitution of ‘template<class T> boost::type_traits::yes_type boost::ptr_container_detail::is_nullable(const boost::nullable<T>*) [with T = <missing>]’
/usr/include/boost/ptr_container/nullable.hpp:55:13:   required from ‘const bool boost::is_nullable<ParentClass<int>::SubClass>::value’
/usr/include/boost/mpl/if.hpp:63:11:   required from ‘struct boost::mpl::if_<boost::is_nullable<ParentClass<int>::SubClass>, ParentClass<int>::SubClass, boost::mpl::identity<ParentClass<int>::SubClass> >’
/usr/include/boost/mpl/eval_if.hpp:37:41:   required from ‘struct boost::mpl::eval_if<boost::is_nullable<ParentClass<int>::SubClass>, ParentClass<int>::SubClass, boost::mpl::identity<ParentClass<int>::SubClass> >’
/usr/include/boost/ptr_container/nullable.hpp:69:13:   required from ‘struct boost::remove_nullable<ParentClass<int>::SubClass>’
/usr/include/boost/ptr_container/nullable.hpp:80:55:   required from ‘struct boost::ptr_container_detail::void_ptr<ParentClass<int>::SubClass>’
test.cpp:11:10:   required from ‘struct ParentClass<int>’
test.cpp:16:22:   required from here
test.cpp:8:37: error: invalid use of incomplete type ‘struct boost::ptr_container_detail::void_ptr<ParentClass<int>::SubClass>’
         boost::ptr_vector<SubClass> nodes;
                                     ^~~~~
In file included from /usr/include/boost/ptr_container/detail/reversible_ptr_container.hpp:25,
                 from /usr/include/boost/ptr_container/ptr_sequence_adapter.hpp:20,
                 from /usr/include/boost/ptr_container/ptr_vector.hpp:20,
                 from test.cpp:1:
/usr/include/boost/ptr_container/nullable.hpp:75:16: note: declaration of ‘struct boost::ptr_container_detail::void_ptr<ParentClass<int>::SubClass>’
         struct void_ptr
                ^~~~~~~~

我对这个问题的理解是,它试图解决ParentClass并因此试图解决其方法-someMehtod(...),但是要做到这一点,必须解决定义的SubClass 。一种解决方法是通过将SubClass实例化为ParentClass的成员来强制进行显式实例化:

struct SubClass
{
    boost::ptr_vector<SubClass> nodes;
} member;

还有另外一种更简单的方法吗? :)

旧版本的boost没有出现此问题,其中boost::ptr_vector是通过void*而不是void_ptr模板类实现的。

0 个答案:

没有答案