【问题标题】:Usage of template class with template method in C++C++中模板类与模板方法的使用
【发布时间】:2013-02-22 10:35:51
【问题描述】:

我有一个类,它有一个公共的模板化方法。 这个类有两种行为策略,我想通过类模板传递。

template<class Strategy>
class SomeClass {
public:
    template<class B>
    void ProcessType(){}
};

// And do something like this:
SomeClass<Strategy1> sc();
sc.ProcessType<SomeClassType>();
sc.ProcessType<SomeClassType2>();

SomeClass<Strategy2> sc2();
sc2.ProcessType<SomeClassType>();
sc2.ProcessType<SomeClassType2>();

但是这段代码无法编译。我需要保持这样的用法(仅通过策略进行操作)。

【问题讨论】:

    标签: c++ templates metaprogramming template-classes


    【解决方案1】:

    这就是问题所在:

    SomeClass<Strategy1> sc();
    

    这是一个名为sc 的函数的声明,它不接受任何参数并返回一个SomeClass&lt;Strategy1&gt;。这通常被称为令人烦恼的解析(但不是most vexing parse)。你想要的是:

    SomeClass<Strategy1> sc;
    

    【讨论】:

    • 谢谢,它可以编译。但不建。我尝试在 .cpp 文件中实现此方法,它纠正了此方法的链接错误(未解决的外部...)。
    • @deeptowncitizen 必须在头文件中定义类模板的成员函数。编译器需要能够看到所有翻译单元中的定义。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-12
    • 2013-03-07
    • 1970-01-01
    相关资源
    最近更新 更多