Compiler doesn't see template specialization?

2019-08-08 04:49发布

I have template in my .h file:

template <typename T>
void addToolsAreaItem(){
    T* item = new T(_image, this);
    doSpecifiedStaff<T>(item);
    _tools.addTool(item);
}

and its specialization in .cpp file:

template <>
void ImageWorkspace::addToolsAreaItem<Preview>(){
    _preview = std::make_unique<QGraphicsView>(_splitter);
    _imagesLayout.addWidget(_preview.get());
}

Class Prewiew is empty and is used only for specialize behavior of one case (when preview button is toggled).

But I get compiler error:

imageworkspace.h:45: error: new initializer expression list treated as compound expression [-fpermissive]
     T* item = new T(_image, this);
               ^~~~~~~~~~~~~~~~~~~

imageworkspace.h:45: error: no matching function for call to ‘Preview::Preview(ImageWorkspace*)’
     T* item = new T(_image, this);
               ^~~~~~~~~~~~~~~~~~~

Does compiler see specialization? How to fix it?

Function is called as addToolsAreaItem<Preview>() from sorces.

1条回答
老娘就宠你
2楼-- · 2019-08-08 05:38

You need a forward declaration for the specialization in the header file. Otherwise, other translation units can't see it.

Henri Menke

#include "Image.h"
int main()
{
    Image::addToolsAreaItem<int>();
    system("pause");
}

Image.h header

#pragma once    
#include <iostream>

namespace Image{

    template <typename T>
    void addToolsAreaItem();

    // forward declaration
    template <>
    void addToolsAreaItem<int>();

}

cpp:

#include "Image.h"

template <typename T>
void Image::addToolsAreaItem()
{
    std::cout << typeid(T).name() << std::endl;
}

template <>
void Image::addToolsAreaItem<int>()
{
    std::cout << "Spec: int " << std::endl;
}

Output:

enter image description here

查看更多
登录 后发表回答