gpt4 book ai didi

C++ 模板实例化限制

转载 作者:行者123 更新时间:2023-11-28 08:28:28 25 4
gpt4 key购买 nike

我在类 C 中有一个方法 foo,它调用 foo_1 或 foo_2。这个方法 foo() 必须在 C 中定义,因为 foo() 在 BaseClass 中是纯虚拟的,我实际上必须创建 C 类型的对象。代码如下:

template <class T>
class C:public BaseClass{

void foo() {
if (something()) foo_1;
else foo_2;

}
void foo_1() {
....
}

void foo_2() {
....
T t;
t.bar(); // requires class T to provide a method bar()
....
}
};

现在对于大多数类型 T foo_1 就足够了,但对于某些类型 foo_2 将被调用(取决于某些东西())。但是编译器坚持实例化两个 foo_1和 foo_2 因为可以调用其中任何一个。

这给 T 带来了负担,它必须提供一个酒吧的方法。

我如何告诉编译器以下内容:

  • 如果 T 没有 bar(),仍然允许它作为实例化类型吗?

最佳答案

您可以使用 boost.enable_if。像这样:

#include <boost/utility/enable_if.hpp>
#include <iostream>

struct T1 {
static const bool has_bar = true;
void bar() { std::cout << "bar" << std::endl; }
};

struct T2 {
static const bool has_bar = false;
};

struct BaseClass {};

template <class T>
class C: public BaseClass {
public:
void foo() {
do_foo<T>();
}

void foo_1() {
// ....
}

template <class U>
void foo_2(typename boost::enable_if_c<U::has_bar>::type* = 0) {
// ....
T t;
t.bar(); // requires class T to provide a method bar()
// ....
}

private:

bool something() const { return false; }


template <class U>
void do_foo(typename boost::enable_if_c<U::has_bar>::type* = 0) {
if (something()) foo_1();
else foo_2<U>();
}

template <class U>
void do_foo(typename boost::disable_if_c<U::has_bar>::type* = 0) {
if (something()) foo_1();
// I dunno what you want to happen if there is no T::bar()
}
};

int main() {
C<T1> c;
c.foo();
}

关于C++ 模板实例化限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3151851/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com