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

标签 统计

c++ ×1

c++11 ×1

g++ ×1

templates ×1