相关疑难解决方法(0)

std :: enable_if有条件地编译成员函数

我想尝试一个简单的例子来了解如何使用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)

c++ templates g++ c++11

144
推荐指数
7
解决办法
10万
查看次数

如何有条件地将一个函数添加到类模板?

我有一个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成语,但这将为所有情况定义函数.不是吗?

c++ templates class template-specialization c++11

11
推荐指数
4
解决办法
2588
查看次数

查找模板相等运算符

我想编写一个代理类,该类具有模板值,并且可以与可以与模板进行比较的任何类进行比较。

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)

c++ templates

2
推荐指数
1
解决办法
70
查看次数

标签 统计

c++ ×3

templates ×3

c++11 ×2

class ×1

g++ ×1

template-specialization ×1