【问题标题】:How to avoid specialization after instantiation error?实例化错误后如何避免特化?
【发布时间】:2012-07-16 00:25:39
【问题描述】:

这是简化的问题。

template <class T>
std::string name(const T&);  // This is the template 
                             // I want to explicitly specialize.

class Outer
{
    class Inner
    {
    };

    class Container : public ::Container<Inner> // This causes also an implicit
                                                // specialization of f::name
    {
    };
};

我怎样才能专精

template <class T>
std::string name(const T&);

Outer::Inner

我无法在我考虑过的三个地方声明显式特化:

template <class T>
std::string name(const T&); 

// 1. Here I cannot forward declare a nested class

class Outer
{
    class Inner
    {
    };

    // 2. Here I get error: explicit specialization
    //    in non-namespace scope 'class Outer'

    class Container : public ::Container<Inner>
    {
    };
};

// 3. Here I get error: specialization of '...' after instantiation

我该如何解决这个问题?

【问题讨论】:

    标签: c++ templates nested-class


    【解决方案1】:

    看看this article。您最好只为您想要“专门化”的特定类型编写一个 name 函数:

    std::string name(const Outer::Inner&);
    

    【讨论】:

    • 谢谢!现在我看到它,我对我的想法感到惊讶。只是过载就可以了,对吧?我也会看文章的!
    • 还有一件事。我在哪里声明重载?似乎问题仍然存在。没有地方,原因和模板案例一样。
    • 您可以在任何需要的地方声明它,并在 .cpp 中定义它,就像任何其他函数一样。如果在很多地方都需要它,你可以有专门的 .h 和 .cpp 文件(你也可以使用 inline 将定义放在 .h 中)
    猜你喜欢
    • 2015-04-23
    • 1970-01-01
    • 1970-01-01
    • 2015-04-15
    • 1970-01-01
    • 1970-01-01
    • 2011-12-08
    • 2014-10-01
    • 2019-01-08
    相关资源
    最近更新 更多