2016-12-22 27 views
2

我正在尝试编写一个基于接口的模板实现来定义其模板的模板类。为了澄清我的问题,这里举一个例子。用于实现与模板接口的类的模板

template<typename T> 
class A{ 
    virtual T getValue() = 0; 
} 

class B : public A<int>{ 
    //does some things and implements getValue 
} 

//template definition 
//T should become int by passing class B 
class C{ 
    A* aPointer; 
    T previousValue; 
} 

我试过模板模板(不是打字错误)的语法,在本文中解释得非常好。 What are some uses of template template parameters in C++?。但是因为A的类型在B的定义中是不可行的,所以它不起作用。

我应该如何去创造,确定T.

+0

在'A'中增加'using type = T;'。和'使用T = typename U :: A :: type;'在模板 C类' – Praetorian

回答

2

不能直接的B确定T的类型的模板,但你从它的接口即可。处理此问题的最佳方法是将T的typedef添加到A.

template<typename T> 
class A{ 
    virtual T getValue() = 0; 
public: 
    typedef T ValueType; 
} 

class B : public A<int>{ 
    //does some things and implements getValue 
} 

template<class T> 
class C { 
    A<typename T::ValueType>* aPointer; 
    typename T::ValueType previousValue; 
} 
+0

这几乎工作,除了我需要在T :: ValueType前的'typename' – sqrtroot

0

在类接口中定义一个命名类型别名。

标准库也是这样。

template<typename T> 
class A{ 
    public: 
    using value_type = T; 
    virtual value_type getValue() = 0; 
}; 

class B : public A<int>{ 
public: 
    using A<int>::value_type; 
    //does some things and implements getValue 
    value_type getValue() override { return 0; } 
}; 

//template definition 
//T should become int by passing class B 
template<class Derived> 
class C{ 
public: 
    using value_type = typename Derived::value_type; 
    A<value_type>* aPointer; 
    value_type previousValue; 
}; 

int main() 
{ 
    C<B> c; 

    auto x = c.aPointer->getValue(); 

} 
0

你可以使用一个你甚至不需要给定义的支持函数。
它遵循最小,工作示例:

#include<type_traits> 
#include<utility> 

template<typename T> 
class A{}; 

class B : public A<int>{}; 

template<typename T> 
T a_type(const A<T> &); 

template<typename T> 
class C { 
public: 
    using type = decltype(a_type(std::declval<T>())); 
}; 

int main() { 
    static_assert(std::is_same<C<B>::type, int>::value, "!"); 
} 

这种方法的很大一部分是,你不必修改既不A也不B