gpt4 book ai didi

c++ - 如何在 .cpp 文件中定义模板成员函数的显式特化

转载 作者:行者123 更新时间:2023-12-01 21:48:05 25 4
gpt4 key购买 nike

我试图将模板成员函数的显式特化移至 .cpp 文件,但链接器一直显示“无法解析的外部符号”。

Foo.hpp

struct Color {};

class Foo
{
public:
template<typename T> int add(T b);
template<> int add(Color b);
};

template<typename T>
int Foo::add(T b)
{
return 0;
}

Foo.cpp

#include "Foo.hpp"

template<>
int Foo::add(Color b)
{
return 0;
}
template int Foo::add(Color b);

酒吧.cpp

#include "Foo.hpp"

void f() {
Foo dbg;
dbg.add(5);
dbg.add(Color());
}

我尝试显式实例化 Foo.cpp 中的成员函数。为什么这没有任何效果?

我知道两种解决方案:我可以将 int Foo::add(Color) 的定义移动到 .hpp 中,并将其标记为内联。或者我可以像这样在 Foo.cpp 中强制实例化:

void dummy() {
Foo().add(Color());
}

为什么我不能使用template int Foo::add(Color b)来实例化该函数?我使用了错误的语法吗?

最佳答案

我不确定,但我认为您正在尝试这样做。

在 Foo.h 中

struct Color {};

class Foo
{
public:
template<typename T> int add(T b);
};

// declare, but do not implement, specialization
template<>
int Foo::add<Color>(Color c);

// general implementation
template<typename T>
int Foo::add(T b)
{
return 0;
}

在 Foo.cpp 中

#include "Foo.h"

// explicitly implement
template<>
int Foo::add<Color>(Color b)
{
return 42;
}

最后是main.cpp

#include "Foo.h"

int main()
{
Foo f;
std::cout << f.add(Color()) << '\n';
}

输出

42

关于c++ - 如何在 .cpp 文件中定义模板成员函数的显式特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60338098/

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