在模板,在那里,为什么我必须把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) 与此相关
我想知道嵌套名称说明符究竟是什么?我在草稿中查了一下但是我能理解语法,因为我还没有学过任何编译器设计课程.
void S(){}
struct S{
S(){cout << 1;}
void f(){}
static const int x = 0;
};
int main(){
struct S *p = new struct ::S;
p->::S::f();
S::x;
::S(); // Is ::S a nested name specifier?
delete p;
}
Run Code Online (Sandbox Code Playgroud) 我试图找到关于模板关键字的任何信息用作消除歧义,但没有任何相关信息.可能我正在搜索错误的关键字,但标准中没有.template或 - >模板.谷歌只显示来自不同论坛的GCC问题,但没有真正解释它用于什么.
第11行(在GCC上)没有模板关键字编译的代码无法编译,但我不太确定这是否符合标准.
template<typename B>
struct S1
{
template<typename T> void test() {}
};
template<typename T>
struct S2
{
S2()
{
S1<T>().template test<int>();
}
};
int main()
{
S2<int>();
}
Run Code Online (Sandbox Code Playgroud)
所以我的问题是:为什么这里使用了模板关键字,没有那个关键字会有什么样的歧义?我在哪里可以阅读(我非常感谢链接到标准).
谢谢.
请考虑以下代码:
template <typename T>
class A {
public:
template <typename T2>
const T2* DoSomething() { ... }
};
template <typename T>
class B : public A<T> {
public:
const int* DoSomethingElse() {
return this->DoSomething<int>(); // Compiler wants 'template' keyword here:
// return this->template DoSomething<int>();
}
};
Run Code Online (Sandbox Code Playgroud)
为什么不编译?我理解标准的相关部分是14.2/4,但我不确定我理解为什么这不起作用的细节.有人可以打破该部分的措辞来解释为什么这不起作用?另外,您能否(通常)描述在什么情况下可以省略模板关键字?
请注意,在C++ 11下面的代码不会编译:
template <typename T>
class A {
public:
template <typename T2>
const T2* DoSomething() { ... }
};
class B {
public:
scoped_ptr<A<int>> var_;
const int* …Run Code Online (Sandbox Code Playgroud)