函数模板无法在 VS2019 Express 中编译

function template won't compile in VS2019 express

我有一个项目,里面有很多函数模板,是我在 Visual Studio 2017 年写的,它一直运行良好。现在我必须在 VS2019 中构建它,因为我需要将 lib 包含在另一个用 VS2019 编写的项目中,并且不会构建。

一个函数模板似乎有问题,尽管它实际上并没有抱怨函数本身。当我在代码中调用它时,编译器只是说“找不到标识符”。东西就在命名空间中,但是,即使是 InteliSense 也能看到它并链接到它而不会抱怨。只是编译器不会。

这是有问题的代码:

// declaration

namespace Oparse
{
    // lots of other functions, many of them templates
    template <typename T> OpModel<T> *_ModelPtr(T *receiver) { return new OpModel<T>(receiver); };
}


// Invocation

namespace Oparse
{

        template <class T, class U>
    class OpModelFactory
        : public OpNestable
    {
        public:
        OpModelFactory<T, U>(vector<U*> &receiver) : OpNestable(OP_MODELFACTORY), receiver(receiver) {};
        // other stuff

        void Serialize(string key, stringstream &stream, unsigned int indents)
        {
            
            for (unsigned int i = 0; i < receiver.size(); ++i)
            {
                // check if the instances are really of the type of this OpModel, otherwise there may be duplicates between polymorphic factories populating the same receiver.
                T *currentModel = dynamic_cast<T*>(receiver[i]);
                if (currentModel != NULL)
                {
                    OpModel<T> *parser = _ModelPtr<T>(currentModel);    // <-- identifier not found
                    parser->Serialize(key, stream, indents);
                    delete parser;
                }
            }
        };

        private:
        vector<U*> &receiver;
    }
}

如果我评论那个调用,项目就会构建,尽管在这个地方声明了更多的函数模板。我不知道该怎么做才能让链接器找到它。有没有 Visual Studio wizzards 可以给我提示?我必须诚实地承认,我已经很多年没有使用 IDE,这是我在 Visual Studio 2019 年的第一次...

这是错误的完整输出。还有第二条消息,但我发现它完全没有用:

1>D:\Orbiter_installs\Orbiter2016\Orbitersdk\Oparse\include\OpModel.h(138,27): error C3861: '_ModelPtr': identifier not found
1>D:\Orbiter_installs\Orbiter2016\Orbitersdk\Oparse\include\OpModel.h(152): message : see reference to class template instantiation 'Oparse::OpModelFactory<T,U>' being compiled

不,没有附加的消息。我看到过类似的消息,通常会继续显示“有... $更多信息”,但这就是我得到的全部信息。

存在循环依赖问题

Oparse.h 中,您首先在 Serialize 的实现中包含需要 _ModelPtrOpModel.h,但是 _ModelPtr 仅稍后在 header.

您需要转发声明模板方法。

OpModel.h中,改为这样写:

namespace Oparse
{
    template<typename T> class OpModel;
    template <typename T> OpModel<T>* _ModelPtr(T* receiver);
    // Remaining of OpModel.h...
    typedef map<string, pair<Oparse::OpValue*, vector<Oparse::OpValidator*>>> OpModelDef;
    typedef vector<pair<Oparse::OpValue*, vector<Oparse::OpValidator*>>> OpValues;
    ...