加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在C中创建成员函数模板专业化

发布时间:2020-12-16 07:02:20 所属栏目:百科 来源:网络整理
导读:我正在编写一个类,我想在其中创建成员函数模板特化 namespace aha{class Foo{public: template typename T T To() const { // some code here }};template bool Foo::To bool () const{ // some other code here}} gcc给出错误: Explicit instantiation of
我正在编写一个类,我想在其中创建成员函数模板特化

namespace aha
{
class Foo
{
public:
    template < typename T >
    T To() const
    {
        // some code here
    }
};
template <>
bool Foo::To < bool > () const
{
    // some other code here
}
}

gcc给出错误:

Explicit instantiation of ‘To < bool >’ after instantiation

我想只使用成员函数的模板特化来实现它,以便我的库的用户在将Foo转换为不同的数据类型时获得相同的功能

Foo obj;
bool b( obj.To < std::string > () );
int i( obj.To < int > () );
float f( obj.To < float > () );

等等.

请让我知道我在代码中做错了什么.

解决方法

Explicit instantiation of ‘To < bool >’ after instantiation

以上说明了一切:它在使用它的通用版本后变得专业化.

函数模板特化可以通过重载来模拟,这是一种更灵活的机制(例如,没有对函数模板进行部分特化,但是可以通过重载实现所需的效果):

template<class T> struct Type {}; // similar to boost::type<>

class Foo
{
    template<class T>
    T doTo(Type<T>) const; // the generic version

    bool doTo(Type<bool>) const; // an overload for bool only
    // add more overloads as you please

public:
    template < typename T >
    T To() const {
        return this->doTo(Type<T>());
    }
};

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读