在模板,在那里,为什么我必须把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) 有时我看到gcc在使用模板时吐出的一些非常难以理解的错误消息......具体来说,我遇到了一些问题,看似正确的声明引起了非常奇怪的编译错误,通过在"typename"关键字前加上前缀而神奇地消失了声明的开头...(例如,就在上周,我宣布两个迭代器作为另一个模板化类的成员,我必须这样做)...
关于typename的故事是什么?
查看二叉树的源代码,我找到以下函数:
//definition of BTR,in case you'd want to know
template< class Type>
struct BTR
{
// The item saved to that specifiec position into the tree
Type value;
// Points to the left leaf
BTR<Type>* left;
// Points to the right leaf
BTR<Type>* right;
};
//why typename?
template< class Type>
BTR<Type>* CreateEx(typename const std::vector<Type>::iterator start,typename const std::vector<Type>::iterator end)
{
//definition
}
Run Code Online (Sandbox Code Playgroud)
现在,让我对这个功能感到困惑的是它的参数.为什么需要关键字typename?因为如果我删除这两个类型名称,我的编译器开始抱怨并说我应该在标识符'start'之前加上')'.如果我更改了参数以便函数使用两个向量而不是两个迭代器并删除了类型名称,我的编译器就会停止抱怨(当然,该函数不再起作用).
// perfectly acceptable!
template< class Type>
BTR<Type>* CreateEx( const std::vector<Type> start, const std::vector<Type> end)
Run Code Online (Sandbox Code Playgroud)
所以我似乎需要关键字,因为该函数需要两个迭代器.但是为什么在这样的情况下这个关键字是必要的呢?
我正在尝试实现一个允许我这样调用的函数
// veca is a vector of tuples in my case
columnViewOfTuple<0>(veca);
Run Code Online (Sandbox Code Playgroud)
我实现了如下功能
template<int N>
struct myfunction {
template<typename T, typename R>
std::vector<R> operator() (T& container)
{
std::vector<R> myvector;
for(typename T::iterator it = container.begin(); it!=container.end(); it++)
myvector.push_back((R)(*it).template get<N>());
return myvector;
}
};
Run Code Online (Sandbox Code Playgroud)
每当我调用myfunction <0>(vec5)时,其中vec5是元组的一些向量,它说
main.cpp:在函数'int main()'中:main.cpp:156:错误:冲突声明'myfunction <0> vec5'main.cpp:155:错误:'vec5'的前一个声明为'main() :: vec1_t vec5'
你们知道如何解决这个问题吗?
谢谢