Reputation: 537
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.
Upvotes: 1
Views: 549
Reputation: 1209
You need a forward declaration for the specialization in the header file. Otherwise, other translation units can't see it.
#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:
Upvotes: 3