码迷,mamicode.com
首页 > 编程语言 > 详细

g++编译时C++类中模板成员函数特化编译报错

时间:2020-04-16 19:34:28      阅读:89      评论:0      收藏:0      [点我收藏+]

标签:c++类   ble   stat   func   exp   int()   hat   mes   let   

特化需要在命名空间里做,不能在类中直接特化一个类模板,但可以放到类外来做。也可在类之内用偏特化,然后传入一个dummy template argument。

 

来源:https://stackoverflow.com/questions/3052579/explicit-specialization-in-non-namespace-scope

template<typename T>
class CConstraint
{
public:
CConstraint()
{
}

virtual ~CConstraint()
{
}

template <typename TL>
void Verify(int position, int constraints[])
{ 
}

template <>
void Verify<int>(int, int[])
{ 
}
};
Compiling this under g++ gives the following error:

Explicit specialization in non-namespace scope ‘class CConstraint‘

In VC, it compiles fine. Can anyone please let me know the workaround?

原因:

VC++ is non-compliant in this case - explicit specializations have to be at namespace scope. C++03, §14.7.3/2:

An explicit specialization shall be declared in the namespace of which the template is a member, or, for member templates, in the namespace of which the enclosing class or enclosing class template is a member.
An explicit specialization of a member function, member class or static data member of a class template shall be declared in the namespace of which the class template is a member.

Additionally you have the problem that you can‘t specialize member functions without explicitly specializing the containing class due to C++03, §14.7.3/3, so one solution would be to let Verify() forward to a, possibly specialized, free function:namespace detail {

template <typename TL> void Verify (int, int[]) {}
template <> void Verify<int>(int, int[]) {}
}

template<typename T> class CConstraint {
// ...
template <typename TL> void Verify(int position, int constraints[]) {
detail::Verify<TL>(position, constraints);
}
};

 

 

来源:https://www.zhihu.com/question/54468727 

class A {
public:
template <typename T, typename = void>
struct B { T value; };
template <typename X>
struct B<int, X> { bool value; };
B<double> dvalue;
B<int> ivalue;
};

 

g++编译时C++类中模板成员函数特化编译报错

标签:c++类   ble   stat   func   exp   int()   hat   mes   let   

原文地址:https://www.cnblogs.com/gelare/p/12714915.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!