首页 > 解决方案 > 由于继承,模板化函数的多个函数定义

问题描述

由于使用模板化参数和继承的函数,我无法使用 VS2015 编译我的程序。

错误就是这个

我正在努力实现以下目标:

class A
{
    //do something
};

class B : public A
{
    //do something
};

template <typename T>
class Foo {
    template <typename T>
    friend void function(Foo<T> & sm) {
        //do something
    }
};

void main()
{
    Foo<A> test;
    Foo<B> test2;
};

我确实理解错误的含义,但我不明白它为什么会发生。

我想function是用两个不同的签名创建的:

void function(Foo<A> & sm);void function(Foo<B> & sm);

多定义怎么算?

编辑 - 完整的错误信息: Error C2995 'void function(Foo<T> &)': function template has already been defined

EDIT² - 从头开始 在此处输入图像描述

标签: c++inheritancefriend

解决方案


Clang 和 MS 都有同样的抱怨。删除第二个模板说明符,它将编译。

class A{};
class B : public A{};

template <typename T>
class Foo {

//  template <typename T>
    friend void function(Foo<T> & sm) {
    }
};

int main()
{
    Foo<A> test;
    Foo<B> test2;
};

T已经为类指定了Foo它的友元函数。template如果功能有差异,您会稍等一下,例如:

class A{};
class B : public A{};

template <typename T>
class Foo {

    template <typename U>
    friend void function(Foo<T> & sm, U another) {
    }
};

int main()
{
    Foo<A> test;
    Foo<B> test2;
};

推荐阅读