【问题标题】:Specializing member template when class has several template parameters?当类有多个模板参数时专门化成员模板?
【发布时间】:2014-07-01 07:45:52
【问题描述】:

在下面的类模板中,我们可以将成员 Foo::Bar() 特化为某种类型,比如 T = int

template <typename T>
class Foo
{
public:
    void Bar()
    {
       std::cout << "generic Bar()" << std::endl;
    }
};

template<>
void Foo<int>::Bar()
{
    std::cout << "specialized Bar()" << std::endl;
}

int main()
{
    Foo<char> generic_foo;
    Foo<int> specialized_foo;

    generic_foo.Bar();
    specialized_foo.Bar();

    return 0;
}

如果类 Foo 有多个模板参数,我们如何做同样的事情:

template <typename T, int N>
class Foo
{
public:
    void Bar()
    {
       std::cout << "generic Bar()" << std::endl;
    }
};

// How can we specialize Foo::Bar() for T = int?

int main()
{
    Foo<char, 0> generic_foo;
    Foo<int, 0> specialized_foo;

    generic_foo.Bar();
    specialized_foo.Bar();

    return 0;
}

我尝试了几种替代方法来将Foo::Bar() 专门用于T = int,包括:

template<int N>
void Foo<int, N>::Bar()
{
    std::cout << "specialized Bar()" << std::endl;
}

但编译器全部拒绝。

【问题讨论】:

    标签: c++ templates c++11


    【解决方案1】:

    模板函数没有部分特化。你应该专攻class

    template<int N>
    class Foo<int, N>
    {
    public:
       void Bar()
       {
          std::cout << "specialized Bar()" << std::endl;
       }
    };
    

    【讨论】:

    • 哦,所以如果 Foo 包含 10 个其他函数成员但只有 Bar() 需要用 T=int 特化,那么所有这 10 个函数的定义都需要重复吗?
    • @user1387866 是的,如果您只想专门化 1 个参数,而不是两者。您还可以编写另一个类,实现方法并从它继承。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多