我想尝试一个简单的例子来了解如何使用std::enable_if
.在我读完这个答案之后,我认为想出一个简单的例子应该不会太难.我想用来std::enable_if
在两个成员函数之间进行选择,并且只允许使用其中一个成员函数.
不幸的是,下面的代码不能用gcc 4.7进行编译,经过数小时和数小时的尝试后我会问你们我的错误是什么.
#include <utility>
#include <iostream>
template< class T >
class Y {
public:
template < typename = typename std::enable_if< true >::type >
T foo() {
return 10;
}
template < typename = typename std::enable_if< false >::type >
T foo() {
return 10;
}
};
int main() {
Y< double > y;
std::cout << y.foo() << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
gcc报告以下问题:
% LANG=C make CXXFLAGS="-std=c++0x" enable_if
g++ -std=c++0x enable_if.cpp -o enable_if
enable_if.cpp:12:65: error: `type' in …
Run Code Online (Sandbox Code Playgroud) 这有什么问题:
#include <type_traits>
struct A;
template<typename T>
struct B
{
template<typename=std::enable_if<std::is_copy_constructible<T>::value>>
void f1() {}
};
template<typename T>
struct C {};
// Type your code here, or load an example.
int main() {
// Following fails
B<A> b;
// Could use this:
// b.f1<C>();
// This complies
C<A> c;
return 0;
}
/* This to be in or not doesn't make a difference
struct A
{};
*/
Run Code Online (Sandbox Code Playgroud)
我在这里尝试过:https : //godbolt.org/z/NkL44s,使用了不同的编译器:
我需要为const和非const类型实现两种不同的方法.我已经设法编写工作代码,但我不明白为什么它的一些味道是好的,而其中一些不是.
这是一个简化的例子,我想知道为什么#1有效,但#2不是,和#3对#4相同:
#include <iostream>
#include <vector>
template <typename T>
class X {
public:
// #1 - works
template<typename B = T, typename std::enable_if<std::is_const<B>::value, int>::type = 0>
void foo() {std::cout << "CONST" << std::endl;}
template<typename B = T, typename std::enable_if<std::is_const<B>::value == false, int>::type = 0>
void foo() {std::cout << "NON-CONST" << std::endl;}
// #2 - does not work "no type named 'type' in 'std::__1::enable_if<false, int>'; 'enable_if' cannot be used to disable this declaration"
// template<typename std::enable_if<std::is_const<T>::value, int>::type = 0>
// void …
Run Code Online (Sandbox Code Playgroud)