在模板,在那里,为什么我必须把typename和template上依赖的名字呢?究竟什么是依赖名称?我有以下代码:
template <typename T, typename Tail> // Tail will be a UnionNode too.
struct UnionNode : public Tail {
// ...
template<typename U> struct inUnion {
// Q: where to add typename/template here?
typedef Tail::inUnion<U> dummy;
};
template< > struct inUnion<T> {
};
};
template <typename T> // For the last node Tn.
struct UnionNode<T, void> {
// ...
template<typename U> struct inUnion {
char fail[ -2 + (sizeof(U)%2) ]; // Cannot be instantiated for any …Run Code Online (Sandbox Code Playgroud) 在编译c ++模板代码时,此站点上存在许多问题.解决此类问题的最常见方法之一是在程序代码的正确位置添加typename(并且不常使用template)关键字:
template<typename T>
class Base
{
public:
typedef char SomeType;
template<typename U>
void SomeMethod(SomeType& v)
{
// ...
}
};
template<typename T>
class Derived : public Base<T>
{
public:
void Method()
{
typename Base<T>::SomeType x;
// ^^^^^^^^
this->template SomeMethod<int>(x);
// ^^^^^^^^
}
};
Run Code Online (Sandbox Code Playgroud)
是否存在使用和不使用关键字编译的代码typename并给出不同的结果(例如输出字符串)?template关键字的类似问题.
如果没有,这些关键词是否真的有必要?
@Paul Evans写了一个很好的答案,但它更适合于 "我在哪里以及为什么要放置"模板"和"typename"关键字?" ,不是我的问题.
@simple给出的示例所需的代码为typename关键字和它的可能的变化.@ Jarod42给出了另一个没有任何模板的变体,这可能是一个 gcc bug,因为它不能用clang编译.