如何使用附加模板参数编写“原位”方法

时间:2013-04-15 07:25:59

标签: c++ templates inline

我有以下代码(也可在http://ideone.com/6ozZrs获得):

#include <iostream>

template<class T>
class MyClass{
    public:
        inline MyClass(const T &t);
        template<class C>
        void MyUberFunction(const C &c)
        {
            std::cout<<"My t: "<<m_t<<std::endl;
            std::cout<<"Do uber things with: "<<&c<<std::endl;
        }
    private:
        T m_t;
};

template<class T>
MyClass<T>::MyClass(const T &t):
    m_t(t)
{
}

int main(int argc, char *argv[])
{
    MyClass<int> myInstance(1337);
    myInstance.MyUberFunction("Another type");

    return 0;
}

MyUberFunction方法采用一组不同的模板参数,然后是其类。我如何拆分它的声明和定义(就像我为类构造函数所做的那样)?

1 个答案:

答案 0 :(得分:8)

您可以将此语法用于类外定义:

template<class T> // <== The class template parameters first
template<class C> // <== The member function template parameters after
void MyClass<T>::MyUberFunction(const C &c)
{
    std::cout<<"My t: "<<m_t<<std::endl;
    std::cout<<"Do uber things with: "<<&c<<std::endl;
}

以下是您修改过的代码编译的live example