模板专业化不明确

Ambiguous template specialization

本文关键字:不明确 专业化      更新时间:2023-10-16

我有一个带有paint()模板函数的Painter模板类。我正在使用标记来专门化模板类中的模板函数。我在Painter.h中放置了模板函数paint()的定义,在Painter.cpp中放置了重载函数的定义。

当我在Painter.cpp中显式实例化paint()时,我遇到编译器错误我的要求是我需要在Painter.cpp文件中实现重载函数paint(ColorTag<Color::RED>)

源文件如下:

油漆工.h

#include <iostream>
enum class Color {
    RED = 0,
    GREEN = 1,
    BLUE = 2
};
template<Color>
struct ColorTag {
};
template<typename T>
class Painter {
public:
    template<Color MyColor>
    void paint(ColorTag<MyColor>);
    void paint(ColorTag<Color::RED>);
};
template<typename T>
template<Color MyColor>
void Painter<T>::paint(ColorTag<MyColor>){
    std::cout << "General" << std::endl;
}

画家.cpp

#include "Painter.h"
template<typename T>
void Painter<T>::paint(ColorTag<Color::RED>){
    std::cout << "RED" << std::endl;
}
template void Painter<int>::paint(ColorTag<Color::RED>);

Main.cpp

#include "Painter.h"
int main(){
    Painter<int> painter;
    painter.paint(ColorTag<Color::RED>());
    return 0;
}

使用编译

g++ Main.cpp Painter.cpp -std=c++11

当我在Painter.cpp 中显式实例化paint()时,我得到了以下编译器错误

Painter.cpp:8:15: error: ambiguous template specialization ‘paint<>’ for ‘void Painter<int>::paint(ColorTag<(Color)0>)’
 template void Painter<int>::paint(ColorTag<Color::RED>);
               ^
Painter.cpp:4:6: note: candidates are: void Painter<T>::paint(ColorTag<(Color)0>) [with T = int]
 void Painter<T>::paint(ColorTag<Color::RED>){
      ^
In file included from Painter.cpp:1:0:
Painter.h:20:10: note:                 template<Color MyColor> void Painter<T>::paint(ColorTag<MyColor>) [with Color MyColor = MyColor; T = int]
     void paint(ColorTag<MyColor>);

我尝试过的

首先我创建了一个名为instantiatePaint()的模板函数来调用paint()函数。然后我将它放置并实例化在Painter.cpp文件中。这起到了作用。但这种感觉有点尴尬。

template<typename T>
template<Color MyColor>
void Painter<T>::instantiatePaint(ColorTag<MyColor>){
    paint(ColorTag<MyColor>());
}
template void Painter<int>::instantiatePaint(ColorTag<Color::RED>);

其次将重载函数定义从Painter.cpp移动到Painter.h。这起作用,但打破了我在Painter.cpp中重载函数paint(ColorTag<Color::RED>)的要求。

有没有更好的方法来解决这个问题,或者到底是什么导致了歧义?

您想要的是T = int的显式专用化,因此正确的语法是:

template<> 
void Painter<int>::paint(ColorTag<Color::RED>);

使用这种语法,g++和clang都可以编译代码。实例

为什么不能初始化整个类而不是函数?

template class Painter<int>;
#include <iostream>
enum Color {
    RED = 0,
    GREEN = 1,
    BLUE = 2
};
template<Color color = Color::RED>
struct ColorTag 
{
    // your Implementation
};
template<>
struct ColorTag <Color::RED>
{
    // your Implementation specific to Color::RED
};
template<typename T>
class Painter {
public:
    // template specialization can not apply on method level
    // use class or struct
    template<Color MyColor> 
    void paint(ColorTag<MyColor>);
};
template<typename T>
template<Color MyColor>
void Painter<T>::paint(ColorTag<MyColor> colorTag)
{
    std::cout << "General"<<std::endl;
}

在visual Studio 2012上运行良好不确定Gcc