模板方法在C ++中相互调用

时间:2018-06-04 21:59:26

标签: c++ templates

我有2个类,其中的方法相互调用。其中一个是模板方法:

// Foo.h
class Foo {
public:
    void foo_method() {
        Bar::bar_method();
    }

    template <typename U>
    static void foo_other_method() {
        // some code
    }
};

// Bar.h
class Bar {
public:
    static void bar_method() {
        Foo::foo_other_method<int>();
    }
};

我称之为:

Foo f;
f.foo_method();

如何在#includeFoo.h中安排Bar.h指令,以便此代码编译?

1 个答案:

答案 0 :(得分:1)

移动if的实施,以便Foo::foo_method()的定义可用。

由于它不是函数模板,因此可以将其移动到.cpp文件。

foo.h中:

Bar

Bar.h:

#pragma once
class Foo {
public:
    void foo_method();

    template <typename U>
    static void foo_other_method() {
        // some code
    }
};

Foo.cpp中:

#pragma once
// Need this so Foo::foo_other_method() can be used.
#include "Foo.h"
class Bar {
public:
    static void bar_method() {
        Foo::foo_other_method<int>();
    }
};