Chr*_*eck 2 c++ inheritance templates template-meta-programming c++11
我最近被一些代码示例搞糊涂了 - 有时看起来继承基类暴露的typedef有效,有时它似乎没有.
我的问题是
这是一些特定的代码:
// First example: Inheriting `static const int ...`
// Basic TypeList object
template<typename... Ts>
struct TypeList {
static const int size = sizeof...(Ts);
};
// Repeat metafunction
template<typename T>
struct repeat;
template<typename... Ts>
struct repeat<TypeList<Ts...>> : TypeList<Ts..., Ts...> {};
// Checks
typedef TypeList<int, float, char> MyList;
static_assert(MyList::size == 3, "D:");
static_assert(repeat<MyList>::size == 6, "D:");
// Second example: Inheriting typedefs
// Meta function to compute a bundle of types
template <typename T>
struct FuncPtrTypes {
typedef int result_type;
typedef T input_type;
typedef result_type(*func_ptr_type)(input_type);
};
// template <typename T, typename FuncPtrTypes<T>::func_ptr_type me>
// struct FuncPtr : FuncPtrTypes<T> {
// static result_type apply(input_type i) {
// return me(i);
// }
// };
//
// Doesn't compile (?): clang 3.6:
// main.cpp:34:9: error: unknown type name 'result_type'
// static result_type apply(input_type i) {
// ^
// main.cpp:34:27: error: unknown type name 'input_type'
// static result_type apply(input_type i) {
// ^
//
// g++ 4.8.4:
// main.cpp:34:9: error: ‘result_type’ does not name a type
// static result_type apply(input_type i) {
// ^
// main.cpp:34:9: note: (perhaps ‘typename FuncPtrTypes<T>::result_type’ was intended)
// This compiles but is clumsy:
template <typename T, typename FuncPtrTypes<T>::func_ptr_type me>
struct FuncPtr {
typedef typename FuncPtrTypes<T>::input_type input_type;
typedef typename FuncPtrTypes<T>::result_type result_type;
static result_type apply(input_type i) {
return me(i);
}
};
// A non-template example:
struct foo {
typedef int bar;
};
struct baz : foo {};
typedef baz::bar bazbar;
// ^ This compiles... huh??
int main() {}
Run Code Online (Sandbox Code Playgroud)
我们可以将您的失败示例简化为:
template <typename T>
struct Base { using type = T; };
template <typename T>
struct Derived : Base<T>
{
type mem; // error: 'type' does not name a type
};
Run Code Online (Sandbox Code Playgroud)
问题是type这里是一个从属名称.这取决于上T.不能保证,对于给定的T,没有一些专业化Base<T>没有命名type.因此,类模板的基本模板不是标准名称查找的一部分,因此您必须对其进行限定:
Base<T>::type mem;
Run Code Online (Sandbox Code Playgroud)
虽然现在我们违反了规则,该规则表明除非明确说明,否则不会将依赖名称视为类型,因此您需要:
typename Base<T>::type mem;
Run Code Online (Sandbox Code Playgroud)
OP中提出的其他案例都不依赖于对从属名称的不合格查找.
要返回到特定问题,这不会编译:
static result_type apply(input_type i) {
Run Code Online (Sandbox Code Playgroud)
因为result_type并且input_type是依赖类型,所以必须限定并加上前缀typename:
static typename FuncPtrTypes<T>::result_type apply(typename FuncPtrTypes<T>::input_type i) {
Run Code Online (Sandbox Code Playgroud)
或者,如果您愿意,可以使用using声明简单地将两个名称都带入:
using typename FuncPtrTypes<T>::input_type;
using typename FuncPtrTypes<T>::result_type;
static result_type apply(input_type i) {
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2184 次 |
| 最近记录: |