gpt4 book ai didi

c++ - `enable_if()` 禁用模板类的静态成员函数声明

转载 作者:行者123 更新时间:2023-12-01 13:13:04 25 4
gpt4 key购买 nike

我试图在模板类中声明函数,以便函数声明依赖于模板类型参数。

template<typename T>
struct Block
{
static bool parse(int32_t index,
const typename std::enable_if<std::is_class<T>::value, T>::type& value);

static bool parse(int32_t index,
typename std::enable_if<!std::is_class<T>::value, T>::type value);
....

};

所以我想说, Block<uint16_t>Block<std::string>parse()声明为:
bool parse(int32_t index, const std::string& value);
or
bool parse(int32_t index, uint16_t value);

但我收到错误: 'enable_if' cannot be used to disable this declaration
...typename std::enable_if<!std::is_class<T>::value, T>::type value);

你能帮我正确声明函数吗?
谢谢。

最佳答案

Enable_if 仅适用于推导的上下文。在您的示例中,扣除是在上课时间完成的。当您使用这些函数时,T 已经是已知的,因此无需推论。

您可以创建一个多余的模板参数,将其默认类型设置为 T,然后对其进行推断。

template<typename T>
struct Block
{
// now parse has to deduce U
template<typename U=T>
static bool parse(int32_t index,
typename std::enable_if<!std::is_class<U>::value, T>::type value);

您的来电者永远不会知道 parse实际上有一个模板参数,但现在你可以在它上面做所有花哨的事情。

关于c++ - `enable_if()` 禁用模板类的静态成员函数声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58812977/

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