gpt4 book ai didi

c++ - *nix 上的模板方法特化

转载 作者:IT王子 更新时间:2023-10-29 01:27:37 26 4
gpt4 key购买 nike

我有一个变体类,它使用一些函数模板专门化来获取和设置不同的类型,这些类型在 Visual Studio 2010 中编译并运行良好。但是这个代码位于一个通用的解决方案中,它也需要在 redhat、ubuntu 等上编译.

我在非命名空间范围内收到一条关于显式特化的错误。我认为简单的解决方法是在类的外部简单地定义我的特化,并在同一命名空间中为该类使用范围限定符。

但是现在我收到错误消息,指出在实例化之后会发生特化,因为类中用于从各种类型转换的其他方法正在类中使用此模板。

那么做这样的事情的正确方法是什么:

namespace Example
{
class CSomeVariant
{
public:
bool toString(std::string& out)
{
return get(out);
}
private:
template <typename T>
bool get(T& val)
{
try {
val = boost::any_cast<T>(m_stored);
}
catch (...) {
return false;
}
return true;
}

boost::any m_stored;
};

template<>
bool CSomeVariant::get(std::string& val)
{
try {
if (m_stored.type() != typeid(std::string))
val = convertToString();
else
val = boost::any_cast<std::string>(m_stored);
}
catch(...) {
return false;
}
return true;
}
}

注意:这不是实际代码,但我相信它显示了问题。

最佳答案

问题是您在类定义中使用了 get() 函数,然后在之后对其进行特殊化,这是不允许的。来自14.7.3第6段

If a template, a member template or the member of a class template is explicitly specialized then that specialization shall be declared before the first use of that specialization that would cause an implicit instantiation to take place, in every translation unit in which such a use occurs; no diagnostic is required. If the program does not provide a definition for an explicit specialization and either the specialization is used in a way that would cause an implicit instantiation to take place or the member is a virtual member function, the program is ill-formed, no diagnostic required.

一个解决方案是重新排序类定义,以便在任何使用之前声明特化。在这种情况下,我能够将函数的内联使用移动到特化之后。

#include <string>
#include <boost/any.hpp>
namespace Example
{
class CSomeVariant
{
public:
bool toString(std::string& out);

private:
template <typename T>
bool get(T& val)
{
try {
val = boost::any_cast<T>(m_stored);
}
catch (...) {
return false;
}
return true;
}

boost::any m_stored;
};

template<>
bool CSomeVariant::get(std::string& val)
{
try {
if (m_stored.type() != typeid(std::string))
val = convertToString();
else
val = boost::any_cast<std::string>(m_stored);
}
catch(...) {
return false;
}
return true;
}


inline bool CSomeVariant::toString(std::string& out)
{
return get(out);
}
}

关于c++ - *nix 上的模板方法特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10438624/

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