[英]Conditionally enable member function depending on template parameter
我正在努力編譯下面的代碼。 我只想在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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.