为什么通过 CRTP 访问派生类中的 typedef 时会出现错误
Why do I get an error when accessing a typedef in a derived class via CRTP?
我很难理解为什么下面的代码无法编译 - 有人可以解释一下吗?
如何从基类访问派生类中的 typedef?
template<class Derived>
struct Test
{
template<class T>
typename Derived::value_type foo(T);
};
struct Derived : public Test<Derived>
{
typedef int value_type;
};
在声明Derived
时,Derived
还不是一个完整的类型 - 你才刚刚开始声明它!因此,在专用化Test<Derived>
中,模板参数是不完整的类型,因此您不能引用嵌套名称,例如Derived::value_type
- 这是循环逻辑。
您可以通过使返回类型成为单独的参数来分解问题:
template <typename T, typename R> struct Test
{
template <typename U> R foo(U);
};
template <typename R>
struct BasicDerived : public Test<BasicDerived, R>
{
typedef R value_type;
};
typedef BasicDerived<int> Derived;
不能直接在基类中访问模板类typedef
或成员,因为此时它不是完整的类型。 允许这样做会导致循环行为:
template<class Derived>
struct Test
{
typedef typename Derived::value_type foo;
};
struct Derived : public Test<Derived>
{
typedef Test<Derived>::foo value_type;
};
但是,您可以在方法中引用模板类的成员,因为它们直到以后才会实例化:
template<class Derived>
struct Test
{
void foo() { typename Derived::value_type bar; }
};
struct Derived : public Test<Derived>
{
typedef int value_type;
};
或者,根据您要尝试的内容,可以将 typedef 作为附加模板参数传递:
template<typename value_type, class Derived>
struct Test
{
template<class T>
value_type foo(T);
};
struct Derived : public Test<int, Derived>
{
typedef int value_type;
};
相关文章:
- 使用typedef'ed返回类型声明友元函数时出现编译器错误
- typedef名称与可变模板参数名称一致时出现GCC错误
- 模板中的Typedef导致阴影模板parm错误
- 类之间的 TypeDef 错误C++
- 错误:使用 tesseract 引擎时 C++ 中的声明'typedef struct tagBLOB BLOB'冲突
- cppcheck:使用 /typedef 的语法错误
- 如何修复 Typedef 变量未识别错误 C++ (Visual Studio 2017)
- 错误:使用不同类型的 Typedef 重定义
- 使用 Rcpp 和 typedef 时出现编译错误
- C typedef int arr [x] [y]在stackdump错误中失败
- 将指向前向声明类型的指针推送到 typedef'd 向量时出现编译器错误
- 来自 typedef 结构的错误
- 课堂上的Typedef.在另一个类错误中:尚未声明类型
- typedef映射作为返回类型到函数会引发编译器错误
- 将Typedef语句放入类链接链接列表中的C 错误
- C++模板化类中的 typedef 错误
- 即使typename关键字也会抛出Typedef错误
- Typedef错误:把Typedef放在哪里,应该怎么写
- C++中的Typedef错误
- 尝试与 typedef 交朋友时"elaborated type refers to typedef"错误