相关疑难解决方法(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万
查看次数

我可以在成员函数上使用boost :: enable_if吗?

我正在编写模板类,我想允许另一种方法仅存在于某种模板类型.目前,该方法适用于所有模板类型,但会导致所有其他类型的编译错误.

使这更复杂的是它是一个重载的operator().不知道我想要做什么实际上是可能的.

这就是我现在拥有的:

template<typename T, typename BASE>
class MyClass  : public BASE
{
public:

    typename T& operator() (const Utility1<BASE>& foo);
    typename T const& operator() (const Utility2<BASE>& foo) const;
};
Run Code Online (Sandbox Code Playgroud)

我希望T&版本始终可用,但T const&只有Utility2<BASE>有效版本才可用.现在,两种方法都存在,但如果Utility2<BASE>无效,尝试使用const版本会产生奇怪的编译错误.我宁愿有一个明智的错误,甚至是"没有这样的成员函数"错误.

这可能吗?

编辑:阅读了升级文档,这是我提出的,它似乎工作:

template<typename T, typename BASE>
class MyClass  : public BASE
{
public:

    typename T& operator() (const Utility1<BASE>& foo);

    template<typename U>
    typename boost::enable_if<boost::is_same<Utility2<BASE>, U>, T>::type const &
    operator() (const U& foo) const;
};
Run Code Online (Sandbox Code Playgroud)

因此,除非有人试图将它与Utility2一起使用,否则它不存在,并且如果它对该BASE类型有效,则它们只能创建一个Utility2.但是当它对BASE类型无效时,MyClass不会浪费时间创建访问器方法.

c++ templates boost enable-if

7
推荐指数
1
解决办法
3908
查看次数

std :: enable_if使用非类型模板参数

你将如何在一个std::enable_if?中使用非类型模板参数比较?我无法弄清楚如何再次这样做.(我曾经有过这个工作,但是我丢失了代码,所以我无法回头看看,而且我找不到帖子,我找到了答案.)

提前感谢您对此主题的任何帮助.

template<int Width, int Height, typename T>
class Matrix{
    static
    typename std::enable_if<Width == Height, Matrix<Width, Height, T>>::type
    Identity(){
        Matrix ret;
        for (int y = 0; y < Width; y++){
            elements[y][y] = T(1);
        }
        return ret;
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑:修复了注释中指出的缺失括号.

c++ templates c++11

5
推荐指数
1
解决办法
2405
查看次数

标签 统计

c++ ×3

templates ×3

c++11 ×2

boost ×1

enable-if ×1

g++ ×1