我试图找到关于模板关键字的任何信息用作消除歧义,但没有任何相关信息.可能我正在搜索错误的关键字,但标准中没有.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 X>
struct A {
template<int N>
int foo() const {
return N;
}
};
template<typename X>
struct B {
int bar(const A<X>& v) {
return v.foo<13>();
}
};
#include <iostream>
using std::cout;
using std::endl;
int main() {
A<double> a;
B<double> b;
cout << b.bar(a) << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在函数内部,B::bar
编译器抱怨:
错误:类型''和'int'到二进制'operator <'的操作数无效
如果A不是模板,那么一切都很好.
我有一段C++代码如下:
template <typename ...A>
struct CastAll{
template <typename ...B>
void cast_all(void(*fun)(B...), A...as){
//...
}
};
Run Code Online (Sandbox Code Playgroud)
我想要做的是以这样的方式实现cast_all:它将每个参数动态转换为B中的相应类型,然后使用"casted"参数调用给定的函数fun.
例如,在:
struct A{};
struct B : public A{};
void foo(B *b1, B *b2){
//... does something with b1 and b2
}
int main(){
A *a1 = new B();
A *a2 = new B();
CastAll<B*, B*> cast; //used to cast each A* to B*
cast.cast_all<B*, B*>(foo, a1, a2);
}
Run Code Online (Sandbox Code Playgroud)
cast_all应扩展为:foo(dynamic_cast(a1),dynamic_cast(a2));
我看过很多关于可变参数模板的文章.然而,几个小时后,我仍然无法弄明白.
有任何想法吗?
How do I fix this syntax error?
struct A {
template < typename T >
void f () {}
};
template < typename C, typename U >
struct B {
void g () {
U::f < C > (); // expected primary-expression before »>« token
}
};
int main () {
B<int,A> b;
b.g ();
}
Run Code Online (Sandbox Code Playgroud) 可能重复:
令人困惑的模板错误
我有一个带有模板化方法的模板类.现在我有另一个函数,有2个模板参数创建带有第一个模板参数的类,并用第二个函数调用函数.考虑这个例子:
template<class S>
class A {
public:
template<class T>
T f1() {
return (T)0.0;
}
};
template<class T,class CT>
void function() {
A<T> a;
a.f1<CT>(); // gcc error in this line
}
Run Code Online (Sandbox Code Playgroud)
gcc给了我:
error: expected primary-expression before ‘>’ toke
Run Code Online (Sandbox Code Playgroud)
在上面标出的行中.为什么这不起作用,我该如何解决?谢谢!弥敦道