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

为什么未使用的成员模板功能的类模板实例化失败

这有什么问题:

#include <type_traits>

struct A;

template<typename T>
struct B
{
    template<typename=std::enable_if<std::is_copy_constructible<T>::value>>
    void f1() {}
};

template<typename T>
struct C {};


// Type your code here, or load an example.
int main() {
    // Following fails
    B<A> b;
    // Could use this:
    // b.f1<C>();

    // This complies
    C<A> c;

    return 0;
}

/* This to be in or not doesn't make a difference
struct A
{};
*/
Run Code Online (Sandbox Code Playgroud)

我在这里尝试过:https : //godbolt.org/z/NkL44s,使用了不同的编译器:

  • x86-64 gcc 9.2:编译
  • x86-64 gcc(trunk):失败
  • x86-64 clang 6.0.0:编译
  • x86-64 …

c++ templates

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

std :: enable_if用于两种不同的方法实现(4种不同的情况)

我需要为const和非const类型实现两种不同的方法.我已经设法编写工作代码,但我不明白为什么它的一些味道是好的,而其中一些不是.

这是一个简化的例子,我想知道为什么#1有效,但#2不是,和#3对#4相同:

#include <iostream>
#include <vector>

template <typename T>
class X {
public:
    // #1 - works
    template<typename B = T, typename std::enable_if<std::is_const<B>::value, int>::type = 0>
    void foo() {std::cout << "CONST" << std::endl;}
    template<typename B = T, typename std::enable_if<std::is_const<B>::value == false, int>::type = 0>
    void foo() {std::cout << "NON-CONST" << std::endl;}

    // #2 - does not work "no type named 'type' in 'std::__1::enable_if<false, int>'; 'enable_if' cannot be used to disable this declaration"
//    template<typename std::enable_if<std::is_const<T>::value, int>::type = 0>
//    void …
Run Code Online (Sandbox Code Playgroud)

c++ templates

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

标签 统计

c++ ×3

templates ×3

c++11 ×1

g++ ×1