2017-07-14 28 views
3
class Myclass 
{ 

    template <typename T> 
    static T func() 
    { 
     T obj; 
     return obj; 
    } 

    template<> 
    static int func<int>() 
    { 

    } 

}; 

我写了上面的类并试图编译它。 我得到了以下错误:仅用于头文件中的静态模板化成员函数的模板行为

error: explicit specialization in non-namespace scope 'class Myclass'
error: template-id 'func' in declaration of primary template

然后我搬出我的静态函数出方的类是这样的:

namespace helper 
{ 
    template <typename T> 
    static T func() 
    { 
     T obj; 
     return obj; 
    } 

    template<> 
    static int func<int>() 
    { 

    } 
} 

class Myclass 
{ 
    template <typename T> 
    static T func() 
    { 
     helper::func<T>(); 
    } 

}; 

我得到了以下错误:

error: explicit template specialization cannot have a storage class
In static member function 'static T Myclass::func()':

那么当然我内联我的专门功能,它的工作。

namespace helper 
{ 
    template <typename T> 
    static T func() 
    { 
     T obj; 
     return obj; 
    } 

    template<> 
    inline int func<int>() 
    { 

     return 1; 
    } 
} 

class Myclass 
{ 
    template <typename T> 
    static T func() 
    { 
     helper::func<T>(); 
    } 

}; 

我的问题是:
1)我们为什么不能专注的类中的静态成员函数。
2)为什么我们不能拥有静态模板专用功能

+0

@tobi如果你经历了整个故事,你会发现我不得不放弃帮手,因为我无法专注于我的静态成员函数。 –

+0

对不起。我读到这一切,但不知何故,当我达成目标时,我已经忘记了开始。对不起); – user463035818

+0

我认为这里的混乱部分是术语“命名空间范围”。这并不意味着“在用'namespace'声明的块内部”;它意味着“不在类,结构,联合,功能等内”。该文件的开头位于命名空间范围内,因为您放置的任何内容都将放在*全局命名空间*中,而不是类或其他东西。 –

回答

0

据我所知,C++不允许在类级别的成员模板专业化。该特必须在命名空间级别提供,所以你可以声明类外的专业化:

// myclass.h 
class MyClass 
{ 
public: 

    template <class T> 
    void test(T) 
    { 
     std::cout << "non-specialized test" << std::endl; 
    } 

    template <class T> 
    static T myfunc() 
    { 
     std::cout << "non-specialized myfunc" << std::endl; 
     return T{}; 
    } 
}; 


template <> 
inline void MyClass::test(double t) 
{ 
    std::cout << "specialized test" << std::endl; 
} 

template <> 
static double MyClass::myfunc(); 

/*template <> 
static inline void MyClass::myfunc(double) 
{ 
    std::cout << "specialized myfunc" << std::endl; 
}*/ 

然后你提供源文件中的实现:

// myclass.cpp 

template <> 
static double MyClass::myfunc() 
{ 
    std::cout << "specialized myfunc" << std::endl; 
    return 0.0; 
} 

或者,你可以内嵌myfunc()在头文件(就像test()函数)。

关于你的第二个问题,我在VS2015中试过了,它工作。唯一的问题是你缺少返回值。

1

老实说,这两个问题的真正答案可能是“因为”。

您可以专注成员函数模板,它只是成为类外,不能使用static关键字:

struct Myclass { 
    template <class T> 
    static T func() { 
     T obj{}; 
     return obj; 
    } 
}; 

template <> 
int Myclass::func<int>() { return 42; } 

两者大多是语法的原因。这只是你必须记住的其中一件事。

相关问题