我想尝试一个简单的例子来了解如何使用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) 我有一个Matrix类模板如下:
template<typename T, std::size_t nrows, std::size_t ncols>
class Matrix
{
T data[nrows][ncols];
public:
T& operator ()(std::size_t i, std::size_t j)
{
return data[i][j];
}
};
Run Code Online (Sandbox Code Playgroud)
我要的是定义一个.setIdentity()当实例的唯一功能nrows==ncols是true在编译的时候.而且会有任何的定义.setIdentity()时,nrows==ncols是false.
我正在尝试使用的是enable_if成语,但这将为所有情况定义函数.不是吗?
我想编写一个代理类,该类具有模板值,并且可以与可以与模板进行比较的任何类进行比较。
template <class T>
class Proxy {
public:
Proxy(T value) : _value(value) {}
template <class U> // this should exist only if the T == U operator is defined
bool operator==(U const& other) const { return _value == other; }
template <class U> // this should exist only if U == T is defined
friend bool operator==(U const& first, Proxy<T> const& second) const { return first == second._value; }
private:
T _value;
};
Run Code Online (Sandbox Code Playgroud)
例如,由于这是合法代码:
bool compare(std::string first, std::string_view second) { …Run Code Online (Sandbox Code Playgroud)