【问题标题】:How to define a templated method of a class template outside of class body如何在类主体之外定义类模板的模板化方法
【发布时间】:2021-09-26 21:46:57
【问题描述】:

我想在类模板中使用模板化方法。我的意思是该方法的附加“模板化”。以下代码 sn -p 应该解释我想要实现的目标:

#include <iostream>

using namespace std;

// a class with a template parameter
template <size_t SIZE>
class SomeClass {
    public:
        static const size_t size = SIZE; // do something with template parameter SIZE
        
        // declaration AND definition of some templated method within class body
        template <typename T> T someFunction(size_t position) {
            return static_cast<T>(position * size); // just do something with type T
        }
};


int main () {
    
    cout << "Access static information: SomeClass<15>::size = " << SomeClass<15>::size << endl;
    
    SomeClass<10> someclass; // instantiate with template parameter 10
    cout << "Access instance information: size = " << someclass.size << endl;
    cout << "Use someFunction with float return value: someclass.SomeFunction<float>(13) = " << someclass.someFunction<float>(13) << endl;
    return 0;
}

这行得通。但是,我想将someFunction 的定义移出类的主体(我有很多模板特化要编写,我不想弄乱类定义)。这是什么语法?

我知道如何在类体之外为模板化类定义方法,并且我知道如何在类体之外定义非模板类的模板化方法。现在我想同时进行。

【问题讨论】:

  • template &lt;size_t SIZE&gt; template &lt;typename T&gt; T SomeClass&lt;SIZE&gt;::someFunction(size_t position) { ...

标签: c++ templates template-classes


【解决方案1】:

您需要两个模板:一个用于类,一个用于函数。

喜欢:

template<size_t SIZE>
template <typename T>
T SomeClass<SIZE>::someFunction(size_t position) {
    return static_cast<T>(position * size); // just do something with type T
}

【讨论】:

  • 非常感谢!我不知道可以像这样链接模板声明。事后看来很容易,也很合乎逻辑! :-) 对于有同样问题的人来说,只是一些额外的信息:这里的顺序很重要(当然)。首先是类模板声明,然后是方法模板声明。
猜你喜欢
  • 2012-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-12
  • 1970-01-01
  • 1970-01-01
  • 2011-06-11
  • 2023-03-13
相关资源
最近更新 更多