gpt4 book ai didi

c++ - 具有非类型模板参数的方法

转载 作者:行者123 更新时间:2023-11-27 23:54:10 24 4
gpt4 key购买 nike

我想知道创建非类型模板类方法的正确语法是什么。我试过这个,但显然它不起作用:

class A
{
enum B
{
C = 0,
D
};
template <A::B value = A::C>
int fun();
};

template<A::B value>
int A::fun<A::B::C>()
{
return 1;
}

template<A::B value>
int A::fun<A::B::D>()
{
return fun<B>() + 1;
}

我做错了什么?

最佳答案

问题是您的特化语法不正确。它试图对一个函数进行部分特化,但这在这里甚至没有意义——而且无论如何都是不允许的。

您还尝试调用 fun<B>()在第二个专业中,但是B是类型名称而不是枚举的值,因此无法解析调用。

试试这个:

// Removed template argument to make a complete specialization instead of partial.
template<>
int A::fun<A::B::C>()
{
return 1;
}

// Removed template argument to make a complete specialization instead of partial.
template<>
int A::fun<A::B::D>()
{
// Changed template argument from B (which is a type) to C (which is a value of
// type B.
return fun<C>() + 1;
}

关于c++ - 具有非类型模板参数的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43894563/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com