我想尝试一个简单的例子来了解如何使用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) 我正在编写一个简单的向量类,我希望有一些成员函数只能在某些长度的向量中使用(例如,3元素向量的交叉乘积).我偶然发现了std :: enable_if,看起来它可能能够做我想要的,但我似乎无法让它正常工作.
#include <iostream>
#include <type_traits>
template<typename T, unsigned int L>
class Vector
{
private:
T data[L];
public:
Vector<T,L>(void)
{
for(unsigned int i = 0; i < L; i++)
{
data[i] = 0;
}
}
T operator()(const unsigned int i) const
{
return data[i];
}
T& operator()(const unsigned int i)
{
return data[i];
}
Vector<typename std::enable_if<L==3, T>::type, L> cross(const Vector<T,L>& vec2) const
{
Vector<T,L> result;
result(0) = (*this)(1) * vec2(2) - (*this)(2) * vec2(1);
result(1) = (*this)(2) * vec2(0) …Run Code Online (Sandbox Code Playgroud)