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

标签 c++ templates

我正在努力编译以下代码。我只想在 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/

相关文章:

c++ - 类模板参数推导 - clang 和 gcc 不同

c++ - 编写一个模板函数来评估具有任何返回类型的 lambda 函数?

c++ - 调用join时如何修复 `terminate called without an active exception`

c++ - 如何使用 Visual Studio 2008 构建在普通旧 XP SP2 上运行且没有并排 DLL 的 C++ 应用程序?

c++ - 用作模板函数输入的函数的 void 返回值被视为参数

javascript - 在 &lt;script type ="text/template"> 标签中包含 &lt;script&gt; 标签

c++ - 关于特定类容器参数化的模式匹配/SFINAE?

c++ - 如何在自定义 TensorFlow C++ 操作中调用 sgemm

c++ - 如何确定 float 何时通过整数边界

c++ - 在 union 中使用字符数组