2013-12-22 50 views
1

我有以下代码:C++模板类的继承[无法转换模板]

#include <iostream> 
using namespace std; 

template<int k> 
struct Base{ 
    int a = k; 
}; 

struct C1 : Base<1>{}; 
struct C2 : Base<2>{int b;}; 

typedef Base<1> C1T; 


    template< 
      typename BufferType, 

      typename VerticesType, 
      VerticesType BufferType::* VerticesField = nullptr 
      > 
    void t(){}; 


int main() { 
// WHY this work?? 
    t<C1T , int, &C1T::a>(); 

// And this not? 
// t<C1 , int, &C1::a>(); 

// ok. 
// t< Base<1>, int, &Base<1>::a >(); 

// also, ok 
t<C2 , int, &C2::b>(); 
    return 0; 
} 

http://ideone.com/8tWCJS

为什么我不能叫 “T” 就这样?

t<C1 , int, &C1::a>(); 

但是,相反,我得到以下错误:

Could not convert template argument ‘&Base<1>::a’ to ‘int C1::*’

附:我能理解这种行为,如果C1是Typedef的...

+0

嗯......对于初学者没有基础,以衍生转换在成员指针它为什么做,所以这是很好不会自动地做,但我发现你甚至不能施放它。 – uk4321

+0

@Mike - 为什么他们必须是静态成员?这是指向成员的指针http://msdn.microsoft.com/en-us/library/k8336763.aspx – tower120

+0

@ uk4321 - “在成员指针上不进行基于派生的转换” - 这是关于什么的? “但我发现你甚至不能施展它” - 你是什么意思? – tower120

回答

0

尝试:

t<Base<1> , int, &C1::a>(); 
+0

如果你解释了为什么它能正常工作,这将是一个更好的答案 –

+0

@Kate在错误消息中说实话,这是正确的。这和't < Base<1>,int,&Base <1> :: a>();'是等价的。 – 2013-12-22 18:52:04

+0

好的 - 我用typedef变体更新了我的问题。为什么它与typedef协同工作,不能与继承协同工作? – tower120