gpt4 book ai didi

c++ - 了解 C++ 成员函数模板特化

转载 作者:IT老高 更新时间:2023-10-28 22:37:19 25 4
gpt4 key购买 nike

我有以下类(class):

#pragma once
#include <string>
#include <iostream>

class testclass
{
public:
template <class T> T item(const std::string& key)
{
std::cout << "non-specialized\n";
return T();
}
};

对于 item 方法,我想为字符串提供一个特化。我尝试通过以下方式执行此操作(在 testclass.cpp 中):

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

template<> std::string testclass::item(const std::string& key)
{
std::cout << "specialized\n";
return std::reverse(key.begin(), key.end());
}

然后我尝试像这样调用函数:

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

int main()
{
testclass t;
std::string key = "foo";
t.item<int>(key);
std::string s = t.item<std::string>(key);
std::cout << s << std::endl;
}

但是,输出是

$ ./a.out
non-specialized
non-specialized
(empty line)

我异常(exception)的是

$ ./a.out
non-specialized
specialized
oof

我怎样才能正确地做到这一点?我正在使用 g++ 4.5.2 来编译程序。

编辑:

解决方法是item的特化的整个定义到 testclass.h (但不进入类)。我在程序中有其他错误,例如不包括<algorithm> (用于反向),并且错误地认为它会返回反转的字符串。为实现异常行为,.cpp 文件为空,头文件内容如下:

#pragma once
#include <string>
#include <iostream>
#include <algorithm>

class testclass
{
public:
template <class T> T item(const std::string& key)
{
std::cout << "non-specialized\n";
return T();
}
};

template<> std::string testclass::item(const std::string& key)
{
std::cout << "specialized\n";
std::string s = key;
std::reverse(s.begin(), s.end());
return s;
}

最佳答案

问题归结为头文件中没有模板的常见问题。编译器在处理 main 时看不到特化,它会为 std::string 生成自己的通用模板的实例化。这违反了 ODR,因为现在在同一个程序中 std::string 有 2 种不同的特化,但编译器不需要对其进行诊断。

简单的解决方案是在头文件中声明/定义特化,以便编译器可以使用它,或者至少在处理 main< 时知道不从泛型版本生成特化/p>

关于c++ - 了解 C++ 成员函数模板特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7582548/

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