C++ 如何将模板超类类型传递给模板基类?
我试图继承一个结构,以便添加+=运算符 这段代码似乎是正确的,但无法编译,我从编译器得到的只是:C++ 如何将模板超类类型传递给模板基类?,c++,templates,C++,Templates,我试图继承一个结构,以便添加+=运算符 这段代码似乎是正确的,但无法编译,我从编译器得到的只是: 语法错误:缺少“,”before“代码的问题是,运算符\u type是一个模板,但编译器不知道如何将其视为一个模板,除非您将template关键字放在它前面 #include <iostream> using namespace std;
语法错误:缺少“,”before“代码的问题是,
运算符\u type
是一个模板,但编译器不知道如何将其视为一个模板,除非您将template关键字放在它前面
#include <iostream>
using namespace std;
struct plus_equals
{
template<typename T, typename S>
struct operator_type
{
S& operator+=(const T &other)
{
S* super = (S*)this;
super->value += other;
return *super;
}
};
};
template<typename T, typename OP>
struct Test : OP:: template operator_type<T, Test<T, OP>> // error on this line
{
T value;
Test(T val) : value(val){}
};
int main(int argc, char *argv[])
{
Test<int, plus_equals> test(123);
test += 456;
cout << test.value << endl;
return 0;
}
#包括
使用名称空间std;
结构加_等于
{
模板
结构运算符类型
{
S和运算符+=(常数T和其他)
{
S*super=(S*)这个;
超级->值+=其他;
返回*super;
}
};
};
模板
结构测试:OP::template operator\u type//此行出错
{
T值;
测试(T val):值(val){}
};
int main(int argc,char*argv[])
{
测试(123);
试验+=456;
cout如果您使用模板
关键字来消除歧义,它将编译
struct Test : OP::template operator_type<T, Test<T, OP> >
struct测试:OP::模板运算符\u类型
此处介绍了为什么需要这样做:这里可能有答案,我想您可能是指:模板S和运算符+=(常量U和其他),但这并不能解决问题。这在llvm中为我编译:struct Test:OP::template operator_type
,您指出了错误。噢..哇。我以前从未见过模板的用法,但它确实编译过(vs2013)。如果您回答,我将接受。谢谢如果您知道如何将测试更改为可变模板,并且仍然可以使用它…那也太好了=)我正在使用visual studio。尚未尝试使用clang..看起来是时候了=)@bitwise MSVC以糟糕著称,我也会远离CRTP,除非你真的知道你在做什么(并且需要它),更不用说你让情况变得更复杂了。你如何让我所做的事情变得更简单?@按位我们不知道你用它做什么,但这显然是一种添加+=
运算符的过于复杂的方式,这有什么好处you@bitwise也许只有我一个人,但我认为你的情况非常特殊
#include <iostream>
using namespace std;
struct plus_equals
{
template<typename T, typename S>
struct operator_type
{
S& operator+=(const T &other)
{
S* super = (S*)this;
super->value += other;
return *super;
}
};
};
template<typename T, typename OP>
struct Test : OP:: template operator_type<T, Test<T, OP>> // error on this line
{
T value;
Test(T val) : value(val){}
};
int main(int argc, char *argv[])
{
Test<int, plus_equals> test(123);
test += 456;
cout << test.value << endl;
return 0;
}
#include <iostream>
using namespace std;
template<typename T, typename Orig>
struct operator_type
{
Orig & operator+=(const T &other)
{
static_cast<Orig*>(this)->value += other;
return *static_cast<Orig*>(this);
}
};
template<typename T, template <class,class> class OP>
struct Test : OP<T,Test<T,OP>> // error on this line
{
T value;
Test(T val) : value(val){}
};
int main() {
Test<int,operator_type> t(10);
t += 10;
cout << t.value << endl;
return 0;
}
struct Test : OP::template operator_type<T, Test<T, OP> >