有人会告诉我为什么编译器在我尝试调用成员函数的版本时标记错误 Foo<T>::setValue
涉及超过 1 个模板参数,如下所示。
参见 ideone
class Bar
{
public:
enum TYPE{};
};
//////////////////////////////////////////////////////////////////////////////////////
template<typename T>
class Foo
{
public:
template<typename P>
void setValue1();
template<typename P, int>
void setValue2();
template<typename P, typename P::TYPE>
void setValue3();
private:
T m_value;
};
//////////////////////////////////////////////////////////////////////////////////////
template<typename T>
template<typename P>
void Foo<T>::setValue1()
{
}
template<typename T>
template<typename P, int>
void Foo<T>::setValue2()
{
}
template<typename T>
template<typename P, typename P::TYPE>
void Foo<T>::setValue3()
{
}
//////////////////////////////////////////////////////////////////////////////////////
int main()
{
Foo<Bar::TYPE> f1;
f1.setValue1<Bar>(); // Compiles
f1.setValue2<Bar, int>(); // ERROR
f1.setValue3<Bar, Bar::TYPE>(); // ERROR
return EXIT_SUCCESS;
}
海湾合作委员会错误:
error: no matching function for call to ‘Foo<Bar::TYPE>::setValue2()’
error: no matching function for call to ‘Foo<Bar::TYPE>::setValue3()’
MSVC .NET 2008 错误:
Test6.cpp(60) : error C2975: 'Foo<T>::setValue2' : invalid template argument for 'unnamed-parameter', expected compile-time constant expression
with
[
T=Bar::TYPE
]
Test6.cpp(24) : see declaration of 'Foo<T>::setValue2'
with
[
T=Bar::TYPE
]
Test6.cpp(61) : error C2975: 'Foo<T>::setValue3' : invalid template argument for 'unnamed-parameter', expected compile-time constant expression
with
[
T=Bar::TYPE
]
Test6.cpp(27) : see declaration of 'Foo<T>::setValue3'
with
[
T=Bar::TYPE
]
最佳答案
除了@Jason 提到的问题,您的第二个函数模板将 int
作为其第二个参数,并且您提供了一个类型。
根据@Jason 的帖子将名称更改为 setValue2
,然后将函数调用更改为:
f1.setValue2<Bar, 3>();
我不确定您要用第三个模板函数定义完成什么。看来您应该只需要一个模板参数,因为 P::Type 也可以派生。
我还应该注意到,您的类定义并不十分精确——该类的模板参数是一个typename
,但您传递给它的是Bar::TYPE
是一个 enum
类型。
关于c++ - 成员函数模板参数数量超过 1 时的编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10604990/