gpt4 book ai didi

c++ - 如何在类模板中使用 boost::enable_if

转载 作者:行者123 更新时间:2023-11-30 01:54:53 29 4
gpt4 key购买 nike

我正在尝试使用 boost::enable_if 打开/关闭类模板中的某些函数,但总是出现编译错误 error: no type named "type"in struct boost::enable_if.

我的片段:

#include <iostream>
#include <tr1/type_traits>
#include <boost/utility.hpp>

namespace std {
using namespace tr1;
}

template <typename T1>
struct C {
template< typename T2 >
void test( T2&, typename boost::enable_if<
std::is_const< T1 >, T1 >::type* = 0 ) {

std::cout << "const" << std::endl;
}

template< typename T2 >
void test( T2&, typename boost::disable_if<
std::is_const< T1 >, T1 >::type* = 0 ) {

std::cout << "non-const" << std::endl;
}
};

int main() {
const int ci = 5;
int i = 6;

C<char> c;
c.test(ci);
c.test(i);
return 0;
}

但是下面类似的代码可以正常工作:

#include <iostream>
#include <tr1/type_traits>
#include <boost/utility.hpp>

namespace std {
using namespace tr1;
}

template <typename T1>
struct C {
template< typename T2 >
void test( T2&, typename boost::enable_if<
std::is_const< T2 >, T1 >::type* = 0 ) {

std::cout << "const" << std::endl;
}

template< typename T2 >
void test( T2&, typename boost::disable_if<
std::is_const< T2 >, T1 >::type* = 0 ) {

std::cout << "non-const" << std::endl;
}
};

int main() {
const int ci = 5;
int i = 6;

C<char> c;
c.test(ci);
c.test(i);
return 0;
}

我想要实现的是根据类模板中声明的类型禁用/启用一些成员函数。实际上不需要模板成员函数。它们仅为 SFINAE 添加。

谁能帮忙??

谢谢!

最佳答案

SFINAE (用于实现 enable_if 的机制)仅在函数模板的模板参数的上下文中起作用。在您的情况下, T1 是封闭类模板的模板参数,而不是函数模板本身的模板参数。从函数模板的角度来看,它是一个固定类型,不能按照声明中拼写的方式使用它是一个正常错误,而不是替换失败。

关于c++ - 如何在类模板中使用 boost::enable_if,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21425710/

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