模板难题 我遇到了C++模板难题。我试着把它降到最低限度,但现在我甚至不确定我想做的是否可行。看看下面的代码(在一些.h文件中)
由于第二部分,我得到的错误消息是模板难题 我遇到了C++模板难题。我试着把它降到最低限度,但现在我甚至不确定我想做的是否可行。看看下面的代码(在一些.h文件中),c++,templates,c++11,template-specialization,C++,Templates,C++11,Template Specialization,由于第二部分,我得到的错误消息是 error C3860: template argument list following class template name must list parameters in the order used in template parameter list error C3855: 'A<T>': template parameter 'T' is incompat
error C3860: template argument list following class
template name must list parameters in the
order used in template parameter list
error C3855: 'A<T>': template parameter 'T' is
incompatible with the declaration
错误C3860:类后面的模板参数列表
模板名称必须在列表中列出参数
模板参数列表中使用的顺序
错误C3855:“A”:模板参数“T”为
与声明不符
知道问题出在哪里吗
编辑
为了让问题更具体,我的动机是。我希望上面的函数
f
对T=std::tuple
、T=std::tuple
和T=std::tuple
进行专门化,其中tuple
中的类型仍然未绑定。如果要将另一个模板传递给模板,则必须使用,因此模板的外观如下所示:
//This one works:
A<B1> first;
first.f<int>(5);
//This one does not work:
A<B2<int>> second;
second.f<int>(5);
template<typename T>
class A
{
public:
template<template <typename> class H, typename S>
void f(H<S> x);
};
模板
甲级
{
公众:
模板
空隙f(hx);
};
现在可以将模板传递给模板
我认为如果您的原始模板没有采用这样的参数类型,您就无法专门处理模板参数 您正在尝试部分专门化成员函数模板。恐怕这是不可能的…您的代码有两个问题。首先,第二个专门化是非法的,因为
template<> // parameters useable for the specialization of A you refer to
// since it is a function, no partial specialization is allowed.
template<typename S> // parameters for the function's parameters
void A<B2<S>> // S can not be used here!
::f(S x) // only here
{
}
而且它也很有效
请注意,这可能无法解决您试图解决的问题,它只是解释了发生了什么
考虑您的编辑:我认为您尝试专门化
T=std::tuple
的事实已经指出了方向:T
是A
的模板参数,这就是您应该专门化的。可能是这样的:
template< typename T >
class F // used to implement f(), so you can specialize
// just F/f() instead of the whole class A
{
void f(T x) { /* default impl */ }
};
template< typename T1, typename T2 >
class F< std::tuple< T1, T2 > >
{
void f(T1 x, T2 y) { /* special impl */ }
};
template< typename T >
class A : public F< T >
{
// ...other stuff...
};
模板
类F//用于实现F(),因此可以专门化
//只有F/F()而不是整个类A
{
void f(tx){/*默认impl*/}
};
模板
类F>
{
void f(T1 x,t2y){/*特殊impl*/}
};
模板
A类:公共F
{
//…其他东西。。。
};
你想用这个做什么?也许有更好的办法。这是你想要的吗@Pubby我在末尾添加了一个部分,其中包含了动机。Re:你的编辑:这将是函数模板的部分专业化。不可能。您可以通过将函数委托给类模板来模拟它。或者普通重载如何?@TimothyShields只是使用模板void f(std::tuple)重载代码>然后呢?我现在正在调查这件事…我会给你回复它是否对我有效。看起来很有希望。
template<>
template<typename S>
void A<B2<int>>::f(S x)
{
}
second.f<B2<int>>(5);
B2<int> x;
second.f<B2<int>>(x);
template< typename T >
class F // used to implement f(), so you can specialize
// just F/f() instead of the whole class A
{
void f(T x) { /* default impl */ }
};
template< typename T1, typename T2 >
class F< std::tuple< T1, T2 > >
{
void f(T1 x, T2 y) { /* special impl */ }
};
template< typename T >
class A : public F< T >
{
// ...other stuff...
};