gpt4 book ai didi

c++ - 在哪里放置模板特化

转载 作者:搜寻专家 更新时间:2023-10-31 00:58:38 25 4
gpt4 key购买 nike

我发现模板特化有一个很奇怪的问题。

此处:Type Traits - Explicit template specialization. fails on xcode

这里:C++ template specialization

写着,成员函数模板特化必须在类外,但在同一个命名空间中(是的,如果模板特化在类内,gcc 4.1.x 版本会失败并出现错误)。

因此,如果我将成员函数模板特化移动到类下方,在相同的命名空间中,则 msvc-2010 编译器认为我定义了它两次:我有编译器错误:

error LNK1169: one or more multiply defined symbols found

error LNK2005 with detail description of defining it twice.

如果我将同一命名空间下的模板特化移动到 cpp 文件中,则 msvc-2010 看不到它,并且在尝试对专业参数使用默认模板函数时失败并出现多个错误:

error C2678: binary '>>' : no operator found which takes a left-hand operand of type 'std::istringstream' (or there is no acceptable conversion)

(发生错误是因为它试图调用运算符 >> 到 const char 指针)

所以,当模板特化在类内部时,msvc-2010 对我有用,但 gcc-4.1.x 就不起作用。

最后,我应该在哪里放置模板特化,以便能够在两个编译器中编译它?

这是标题:

#include <iostream>
#include <sstream>
#include <string>
class MyMap
{
public:
template<typename T>
T getValue(std::string phrase, T def)
{
std::istringstream ss(phrase);
T ret;
ss >> ret;
if(ss.fail() || !ss.eof())
return def;
else
return ret;
}

还有这个特化(来自 cpp,但我不知道它必须在哪里):

template<>
std::string MyMap::getValue(std::string phrase, std::string def)
{
return phrase;
}
template<>
const char* MyMap::getValue(std::string phrase, const char* def)
{
return phrase.c_str();
}

专门用于 stringconst char*(正是为了避免 ss >> ret;retconst char 指针)。

示例非常简单。

最佳答案

你可以把它放在类定义之外的头部,像这样:

template<>
inline std::string MyMap::getValue<std::string>(std::string phrase, std::string def)
{
return phrase;
}

template<>
inline const char* MyMap::getValue<const char*>(std::string phrase, const char* def)
{
return phrase.c_str();
}

或者使用您希望它拥有的参数集声明常规方法,并像往常一样在 .cpp 中定义它:

.h

class MyMap
{
// ...
std::string getValue(std::string phrase, std::string def);
const char* getValue(std::string phrase, const char* def);
}

.cpp

std::string MyMap::getValue(std::string phrase, std::string def)    
{
return phrase;
}

const char* MyMap::getValue(std::string phrase, const char* def)
{
return phrase.c_str();
}

关于c++ - 在哪里放置模板特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35115239/

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