编译器没有看到模板专业化? [英] Compiler doesn't see template specialization?

查看:56
本文介绍了编译器没有看到模板专业化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 .h 文件中有模板:

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

及其在 .cpp 文件中的专长:

 模板<>void ImageWorkspace :: addToolsAreaItem< Preview>(){_preview = std :: make_unique< QGraphicsView>(_ splitter);_imagesLayout.addWidget(_preview.get());} 

Class Prewiew 为空,仅用于特殊情况下的一种情况(切换预览按钮时).

但是我得到了编译器错误:

  imageworkspace.h:45:错误:新的初始化程序表达式列表被视为复合表达式[-fpermissive]T * item = new T(_image,this);^ ~~~~~~~~~~~~~~~~~~imageworkspace.h:45:错误:调用"Preview :: Preview(ImageWorkspace *)"没有匹配功能T * item = new T(_image,this);^ ~~~~~~~~~~~~~~~~~~ 

编译器看到专业化了吗?如何解决?

函数从源中称为 addToolsAreaItem< Preview>().

解决方案

您需要在标头中进行专门化的前向声明文件.否则,其他翻译单位将看不到它.

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.

解决方案

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:

这篇关于编译器没有看到模板专业化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆