【问题标题】:How to define a template member function of a template class [duplicate]如何定义模板类的模板成员函数[重复]
【发布时间】:2012-07-09 12:15:39
【问题描述】:

可能重复:
How do I define a template function within a template class outside of the class definition?

在模板类中有模板成员函数的情况下,我正在努力解决语法问题:

template <typename T> class Foo
{
    void Bar(const T * t);
    template <typename T2> void Bar(const T2 * t);
};

template <typename T> void Foo<T>::Bar(const T * t)
{
    // ... no problem ...
}

template <typename T> void Foo<T>::Bar<typename T2>(const T2 * t)
{
    // ... this is where I'm tearing my hair out ...
}

第一个成员函数很好,但是处理模板类的基类型以外的类型的模板成员函数是我遇到问题的地方。对于上述情况,我收到以下错误:

template_problem.cpp:12: error: parse error in template argument list
template_problem.cpp:12: error: expected ‘,’ or ‘...’ before ‘*’ token
template_problem.cpp:12: error: ISO C++ forbids declaration of ‘T2’ with no type
template_problem.cpp:12: error: template-id ‘Bar<<expression error> >’ in declaration of primary template
template_problem.cpp:12: error: prototype for ‘void Foo<T>::Bar(int)’ does not match any in class ‘Foo<T>’
template_problem.cpp:4: error: candidates are: template<class T> template<class T2> void Foo::Bar(const T2*)
template_problem.cpp:7: error:                 void Foo<T>::Bar(const T*)
template_problem.cpp:12: error: template definition of non-template ‘void Foo<T>::Bar(int)’

对于Bar 的模板版本,我还尝试了我能想到的所有其他语法变化。

【问题讨论】:

    标签: c++ templates


    【解决方案1】:
    template<typename T>
    template<typename T2>
    void Foo<T>::Bar(const T2* t) 
    {
         // stop tearing your hair out
    }
    

    【讨论】:

    • template&lt;typename T&gt;template&lt;typename T2&gt;可以换地方吗?
    • @hkBattousai 如果您将Foo&lt;T&gt; 更改为Foo&lt;T2&gt;,那么可以。顺序很重要。
    • 为什么需要将类模板函数定义为 void Foo::Bar() 而不是 void Foo::Bar()?将 添加到 Foo(类名) 的原因是什么?为什么不是普通的 Foo(类名)?
    • @Rahul 因为它是一个模板类并且需要一个模板参数。
    【解决方案2】:
    template <typename T>
    template <typename T2> 
    void Foo<T>::Bar(const T2 * t) {
        // ... this is where I'm tearing my hair out ...
    }
    

    是不是很丑。

    【讨论】:

    • 是的 - 令人惊讶的是,您可以尝试许多不同且看似合乎逻辑的语法变体,而不会偶然发现正确的变体。
    • @PaulR 对于模板来说老实说,它变得如此纠结,以至于我在类定义中编写实现。老实说,我认为这很容易阅读,然后将所有内容与添加的模板垃圾分开。
    • 是的 - 我开始看到这样做的吸引力。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-06
    • 1970-01-01
    • 2023-03-13
    • 2010-12-22
    相关资源
    最近更新 更多