gpt4 book ai didi

c++ - 根据模板参数有条件地启用成员函数

转载 作者:行者123 更新时间:2023-12-05 03:23:56 25 4
gpt4 key购买 nike

我正在努力编译以下代码。我只想在 N=3 时为类 A 启用 foo 函数。

#include <iostream>

template <size_t N>
class A
{
public:
template <size_t n = N, std::enable_if_t<(n == 3)>* = nullptr> int foo(int a);
};

template<size_t N>
template <size_t n = N, std::enable_if_t<(n == 3)>* = nullptr>
int A<N>::foo(int a)
{
return a * 4;
}

int main()
{
A<3> a1;
std::cout << a1.foo(10) << std::endl;

// the below should fail to compile
// A<4> a2;
// std::cout << a2.foo(7) << std::endl;
}

输出

<source>:12:20: error: default argument for template parameter for class enclosing 'int A<N>::foo(int)'
12 | int A<N>::foo(int a)
| ^

最佳答案

无论何时将函数的声明和定义分开,无论它是否是模板函数,默认参数值只能在声明中,而不能在定义中。因此,只需从 foo 的定义中删除默认值,例如:

#include <iostream>

template <size_t N>
class A
{
public:
template <size_t n = N, std::enable_if_t<(n == 3)>* = nullptr> int foo(int a);
};

template<size_t N>
template <size_t n, std::enable_if_t<(n == 3)>*>
int A<N>::foo(int a)
{
return a * 4;
}

Online Demo

关于c++ - 根据模板参数有条件地启用成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72412938/

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