gpt4 book ai didi

c++ - 如何在不将所有相关代码带到 header 的情况下解决模板成员函数的 undefined reference ?

转载 作者:行者123 更新时间:2023-11-30 04:23:57 26 4
gpt4 key购买 nike

foo.h中:

#ifndef FOO_H
#define FOO_H

enum Rat
{
A,
B
};

class Foo
{
public:
template<Rat r>
int aMemberFunc(int, int, int);
};

#endif

foo.cpp中:

#include "foo.h"

namespace {
template<Rat r>
int helper(int a, int b)
{
return a+b*((int) r);
}
}

template<Rat r>
int Foo::aMemberFunc(int a, int b, int c)
{
return a + helper<r>(b,c);
}

main.cpp 中:

#include "foo.h"
#include <iostream>

using namespace std;

int main(void)
{
Foo test;
cout << test.aMemberFunc<B>(1,2,3) << endl;
}

我用 g++ main.cpp foo.cpp 编译,我得到:

main.cpp:(.text+0x88): undefined reference to `int Foo::aMemberFunc<(Rat)1>(int, int, int)'
collect2: ld returned 1 exit status

我不想把东西移到标题中,因为这会带来帮助程序和很多行李,我尝试添加一个文件 fooimpl.cpp:

#include "foo.h"
#include "foo.cpp"

template int Foo::aMemberFunc<A>(int,int,int);
template int Foo::aMemberFunc<B>(int,int,int);

然后用g++ fooimpl.cpp main.cpp foo.cpp编译

这是根据 Dietmar 的建议(谢谢!)但是一旦我在 foo.h 的 header 中添加函数 void rand(); foo.cpp 中的 code>void rand() {} 上述技巧会产生此错误:

foo.cpp:(.text+0x0): `Foo::rand()' 的多重定义/tmp/ccoCtGMk.o:fooimpl.cpp:(.text+0x0): 首先在这里定义

我该如何解决这个问题?

最佳答案

您需要实例化您的函数,而不是专门化它:

#include "foo.h"
#include "foo.cpp"

template int Foo::aMemberFunc<A>(int,int,int);
template int Foo::aMemberFunc<B>(int,int,int);

关于c++ - 如何在不将所有相关代码带到 header 的情况下解决模板成员函数的 undefined reference ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13059437/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com