c++ - 成员函数模板参数数量超过 1 时的编译错误

标签 c++ templates stl

有人会告诉我为什么编译器在我尝试调用成员函数的版本时标记错误 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/

相关文章:

c++ - 是否可以将矩阵与初始化列表相乘?

c++ - 是否会为非类型模板参数的不同值实例化新类

java - 从数据库加载 FreeMarker 模板

c++ - memorystream - stringstream,字符串,其他?

c++ - 基类虚拟析构函数访问冲突

c++ - 将其转换为基类指针是否安全?

c++ - 适用于 Vista/Windows 7 的凭证管理器

c++ - 在 VSCode 上使用 F5 调试失败,提示 "Unable to establish a connection to GDB"

c++ - 实时查看循环缓冲区中的数据

c++ - 模板中的模板。在模板函数中特化模板类